Skip to content

Commit 6979883

Browse files
authored
Merge pull request astaxie#832 from vCaesar/u12-pr
Update install Go and Add en/0.4.x.md syntax highlighting
2 parents 0f425ef + 7e82857 commit 6979883

File tree

7 files changed

+165
-159
lines changed

7 files changed

+165
-159
lines changed

en/01.1.md

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -76,15 +76,15 @@ A 64-bit operating system will show the following:
7676

7777
### Mac
7878

79-
Go to the [download page](https://golang.org/dl/), choose `go1.4.2.darwin-386.pkg` (The later version has no 32-bit download.)for 32-bit systems and `go1.8.darwin-amd64.pkg` for 64-bit systems. Going all the way to the end by clicking "next", `~/go/bin` will be added to your system's $PATH after you finish the installation. Now open the terminal and type `go`. You should see the same output shown in figure 1.1.
79+
Go to the [download page](https://golang.org/dl/), choose `go1.4.2.darwin-386.pkg` (The later version has no 32-bit download.)for 32-bit systems and `go1.8.1.darwin-amd64.pkg` for 64-bit systems. Going all the way to the end by clicking "next", `~/go/bin` will be added to your system's $PATH after you finish the installation. Now open the terminal and type `go`. You should see the same output shown in figure 1.1.
8080

8181
### Linux
8282

83-
Go to the [download page](https://golang.org/dl/), choose `go1.8.linux-386.tar.gz` for 32-bit systems and `go1.8.linux-amd64.tar.gz` for 64-bit systems. Suppose you want to install Go in the `$GO_INSTALL_DIR` path. Uncompress the `tar.gz` to your chosen path using the command `tar zxvf go1.8.linux-amd64.tar.gz -C $GO_INSTALL_DIR`. Then set your $PATH with the following: `export PATH=$PATH:$GO_INSTALL_DIR/go/bin`. Now just open the terminal and type `go`. You should now see the same output displayed in figure 1.1.
83+
Go to the [download page](https://golang.org/dl/), choose `go1.8.1.linux-386.tar.gz` for 32-bit systems and `go1.8.1.linux-amd64.tar.gz` for 64-bit systems. Suppose you want to install Go in the `$GO_INSTALL_DIR` path. Uncompress the `tar.gz` to your chosen path using the command `tar zxvf go1.8.1.linux-amd64.tar.gz -C $GO_INSTALL_DIR`. Then set your $PATH with the following: `export PATH=$PATH:$GO_INSTALL_DIR/go/bin`. Now just open the terminal and type `go`. You should now see the same output displayed in figure 1.1.
8484

8585
### Windows
8686

87-
Go to the [download page](https://golang.org/dl/), choose `go1.8.windows-386.msi` for 32-bit systems and `go1.8.windows-amd64.msi` for 64-bit systems. Going all the way to the end by clicking "next", `c:/go/bin` will be added to `path`. Now just open a command line window and type `go`. You should now see the same output displayed in figure 1.1.
87+
Go to the [download page](https://golang.org/dl/), choose `go1.8.1.windows-386.msi` for 32-bit systems and `go1.8.1.windows-amd64.msi` for 64-bit systems. Going all the way to the end by clicking "next", `c:/go/bin` will be added to `path`. Now just open a command line window and type `go`. You should now see the same output displayed in figure 1.1.
8888

8989
## Use third-party tools
9090

@@ -96,8 +96,8 @@ GVM is a Go multi-version control tool developed by a third-party, like rvm for
9696

9797
Then we install Go using the following commands:
9898

99-
gvm install go1.8
100-
gvm use go1.8
99+
gvm install go1.8.1
100+
gvm use go1.8.1
101101

102102
After the process has finished, you're all set.
103103

@@ -112,16 +112,16 @@ Ubuntu is the most popular desktop release version of Linux. It uses `apt-get` t
112112
### wget
113113
```sh
114114

115-
wget https://storage.googleapis.com/golang/go1.8.linux-amd64.tar.gz
116-
sudo tar -xzf go1.8.linux-amd64.tar.gz -C /usr/local
115+
wget https://storage.googleapis.com/golang/go1.8.1.linux-amd64.tar.gz
116+
sudo tar -xzf go1.8.1.linux-amd64.tar.gz -C /usr/local
117117

118118
# Go environment
119119
export GOROOT=/usr/local/go
120120
export GOBIN=$GOROOT/bin
121121
export PATH=$PATH:$GOBIN
122122
export GOPATH=HOME/gopath
123123
```
124-
Starting from go 1.8,The GOPATH environment variable now has a default value if it is unset. It defaults to $HOME/go on Unix and %USERPROFILE%/go on Windows.
124+
Starting from go 1.8, The GOPATH environment variable now has a default value if it is unset. It defaults to $HOME/go on Unix and %USERPROFILE%/go on Windows.
125125
### Homebrew
126126

127127
Homebrew is a software management tool commonly used in Mac to manage packages. Just type the following commands to install Go.

en/04.1.md

Lines changed: 55 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -1,71 +1,72 @@
11
# 4.1 Process form inputs
22

33
Before we begin, let's take a look at a simple example of a typical user form, saved as `login.gtpl` in your project folder.
4-
5-
<html>
4+
```html
5+
<html>
66
<head>
77
<title></title>
88
</head>
99
<body>
10-
<form action="/login" method="post">
11-
Username:<input type="text" name="username">
12-
Password:<input type="password" name="password">
13-
<input type="submit" value="Login">
14-
</form>
10+
<form action="/login" method="post">
11+
Username:<input type="text" name="username">
12+
Password:<input type="password" name="password">
13+
<input type="submit" value="Login">
14+
</form>
1515
</body>
16-
</html>
17-
16+
</html>
17+
```
1818
This form will submit to `/login` on the server. After the user clicks the login button, the data will be sent to the `login` handler registered by the server router. Then we need to know whether it uses the POST method or GET.
1919

2020
This is easy to find out using the `http` package. Let's see how to handle the form data on the login page.
2121

22-
package main
23-
24-
import (
25-
"fmt"
26-
"html/template"
27-
"log"
28-
"net/http"
29-
"strings"
30-
)
31-
32-
func sayhelloName(w http.ResponseWriter, r *http.Request) {
33-
r.ParseForm() //Parse url parameters passed, then parse the response packet for the POST body (request body)
34-
// attention: If you do not call ParseForm method, the following data can not be obtained form
35-
fmt.Println(r.Form) // print information on server side.
36-
fmt.Println("path", r.URL.Path)
37-
fmt.Println("scheme", r.URL.Scheme)
38-
fmt.Println(r.Form["url_long"])
39-
for k, v := range r.Form {
40-
fmt.Println("key:", k)
41-
fmt.Println("val:", strings.Join(v, ""))
42-
}
43-
fmt.Fprintf(w, "Hello astaxie!") // write data to response
22+
```Go
23+
package main
24+
25+
import (
26+
"fmt"
27+
"html/template"
28+
"log"
29+
"net/http"
30+
"strings"
31+
)
32+
33+
func sayhelloName(w http.ResponseWriter, r *http.Request) {
34+
r.ParseForm() //Parse url parameters passed, then parse the response packet for the POST body (request body)
35+
// attention: If you do not call ParseForm method, the following data can not be obtained form
36+
fmt.Println(r.Form) // print information on server side.
37+
fmt.Println("path", r.URL.Path)
38+
fmt.Println("scheme", r.URL.Scheme)
39+
fmt.Println(r.Form["url_long"])
40+
for k, v := range r.Form {
41+
fmt.Println("key:", k)
42+
fmt.Println("val:", strings.Join(v, ""))
4443
}
45-
46-
func login(w http.ResponseWriter, r *http.Request) {
47-
fmt.Println("method:", r.Method) //get request method
48-
if r.Method == "GET" {
49-
t, _ := template.ParseFiles("login.gtpl")
50-
t.Execute(w, nil)
51-
} else {
52-
r.ParseForm()
53-
// logic part of log in
54-
fmt.Println("username:", r.Form["username"])
55-
fmt.Println("password:", r.Form["password"])
56-
}
44+
fmt.Fprintf(w, "Hello astaxie!") // write data to response
45+
}
46+
47+
func login(w http.ResponseWriter, r *http.Request) {
48+
fmt.Println("method:", r.Method) //get request method
49+
if r.Method == "GET" {
50+
t, _ := template.ParseFiles("login.gtpl")
51+
t.Execute(w, nil)
52+
} else {
53+
r.ParseForm()
54+
// logic part of log in
55+
fmt.Println("username:", r.Form["username"])
56+
fmt.Println("password:", r.Form["password"])
5757
}
58-
59-
func main() {
60-
http.HandleFunc("/", sayhelloName) // setting router rule
61-
http.HandleFunc("/login", login)
62-
err := http.ListenAndServe(":9090", nil) // setting listening port
63-
if err != nil {
64-
log.Fatal("ListenAndServe: ", err)
65-
}
58+
}
59+
60+
func main() {
61+
http.HandleFunc("/", sayhelloName) // setting router rule
62+
http.HandleFunc("/login", login)
63+
err := http.ListenAndServe(":9090", nil) // setting listening port
64+
if err != nil {
65+
log.Fatal("ListenAndServe: ", err)
6666
}
67+
}
6768

68-
69+
```
6970
Here we use `r.Method` to get the request method, and it returns an http verb -"GET", "POST", "PUT", etc.
7071

7172
In the `login` function, we use `r.Method` to check whether it's a login page or login processing logic. In other words, we check to see whether the user is simply opening the page, or trying to log in. Serve shows the page only when the request comes in via the GET method, and it executes the login logic when the request uses the POST method.
@@ -87,7 +88,7 @@ Try changing the value of the action in the form `http://127.0.0.1:9090/login` t
8788
Figure 4.2 Server prints request data
8889

8990
The type of `request.Form` is `url.Value`. It saves data with the format `key=value`.
90-
91+
```Go
9192
v := url.Values{}
9293
v.Set("name", "Ava")
9394
v.Add("friend", "Jess")
@@ -97,7 +98,7 @@ The type of `request.Form` is `url.Value`. It saves data with the format `key=va
9798
fmt.Println(v.Get("name"))
9899
fmt.Println(v.Get("friend"))
99100
fmt.Println(v["friend"])
100-
101+
```
101102
**Tips** Requests have the ability to access form data using the `FormValue()` method. For example, you can change `r.Form["username"]` to `r.FormValue("username")`, and Go calls `r.ParseForm` automatically. Notice that it returns the first value if there are arguments with the same name, and it returns an empty string if there is no such argument.
102103

103104
## Links

en/04.2.md

Lines changed: 39 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -7,17 +7,17 @@ There are two ways of verifying form data that are in common use. The first is J
77
## Required fields
88

99
Sometimes we require that users input some fields but they fail to complete the field. For example in the previous section when we required a username. You can use the `len` function to get the length of a field in order to ensure that users have entered something.
10-
10+
```Go
1111
if len(r.Form["username"][0])==0{
1212
// code for empty field
1313
}
14-
14+
```
1515
`r.Form` treats different form element types differently when they are blank. For empty textboxes, text areas and file uploads, it returns an empty string; for radio buttons and check boxes, it doesn't even create the corresponding items. Instead, you will get errors if you try to access it. Therefore, it's safer to use `r.Form.Get()` to get field values since it will always return empty if the value does not exist. On the other hand, `r.Form.Get()` can only get one field value at a time, so you need to use `r.Form` to get the map of values.
1616

1717
## Numbers
1818

1919
Sometimes you require numbers rather than other text for the field value. For example, let's say that you require the age of a user in integer form only, i.e 50 or 10, instead of "old enough" or "young man". If we require a positive number, we can convert the value to the `int` type first, then process it.
20-
20+
```Go
2121
getint,err:=strconv.Atoi(r.Form.Get("age"))
2222
if err!=nil{
2323
// error occurs when convert to number, it may not a number
@@ -27,55 +27,55 @@ Sometimes you require numbers rather than other text for the field value. For ex
2727
if getint >100 {
2828
// too big
2929
}
30-
30+
```
3131
Another way to do this is by using regular expressions.
32-
32+
```Go
3333
if m, _ := regexp.MatchString("^[0-9]+$", r.Form.Get("age")); !m {
3434
return false
3535
}
36-
36+
```
3737
For high performance purposes, regular expressions are not efficient, however simple regular expressions are usually fast enough. If you are familiar with regular expressions, it's a very convenient way to verify data. Notice that Go uses [RE2](http://code.google.com/p/re2/wiki/Syntax), so all UTF-8 characters are supported.
3838

3939
## Chinese
4040

4141
Sometimes we need users to input their Chinese names and we have to verify that they all use Chinese rather than random characters. For Chinese verification, regular expressions are the only way.
42-
43-
if m, _ := regexp.MatchString("^[\\x{4e00}-\\x{9fa5}]+$", r.Form.Get("realname")); !m {
44-
return false
45-
}
46-
42+
```Go
43+
if m, _ := regexp.MatchString("^[\\x{4e00}-\\x{9fa5}]+$", r.Form.Get("realname")); !m {
44+
return false
45+
}
46+
```
4747
## English letters
4848

4949
Sometimes we need users to input only English letters. For example, we require someone's English name, like astaxie instead of asta谢. We can easily use regular expressions to perform our verification.
50-
51-
if m, _ := regexp.MatchString("^[a-zA-Z]+$", r.Form.Get("engname")); !m {
52-
return false
53-
}
54-
50+
```Go
51+
if m, _ := regexp.MatchString("^[a-zA-Z]+$", r.Form.Get("engname")); !m {
52+
return false
53+
}
54+
```
5555
## E-mail address
5656

5757
If you want to know whether users have entered valid E-mail addresses, you can use the following regular expression:
58-
58+
```Go
5959
if m, _ := regexp.MatchString(`^([\w\.\_]{2,10})@(\w{1,}).([a-z]{2,4})$`, r.Form.Get("email")); !m {
6060
fmt.Println("no")
6161
}else{
6262
fmt.Println("yes")
6363
}
64-
64+
```
6565
## Drop down list
6666

6767
Let's say we require an item from our drop down list, but instead we get a value fabricated by hackers. How do we prevent this from happening?
6868

6969
Suppose we have the following `<select>`:
70-
70+
```html
7171
<select name="fruit">
7272
<option value="apple">apple</option>
7373
<option value="pear">pear</option>
7474
<option value="banana">banana</option>
7575
</select>
76-
76+
```
7777
We can use the following strategy to sanitize our input:
78-
78+
```Go
7979
slice:=[]string{"apple","pear","banana"}
8080

8181
for _, v := range slice {
@@ -84,18 +84,18 @@ We can use the following strategy to sanitize our input:
8484
}
8585
}
8686
return false
87-
87+
```
8888
All the functions I've shown above are in my open source project for operating on slices and maps: [https://github.com/astaxie/beeku](https://github.com/astaxie/beeku)
8989

9090
## Radio buttons
9191

9292
If we want to know whether the user is male or female, we may use a radio button, returning 1 for male and 2 for female. However, some little kid who just read his first book on HTTP, decides to send to you a 3. Will your program throw an exception? As you can see, we need to use the same method as we did for our drop down list to make sure that only expected values are returned by our radio button.
93-
93+
```html
9494
<input type="radio" name="gender" value="1">Male
9595
<input type="radio" name="gender" value="2">Female
96-
96+
```
9797
And we use the following code to validate the input:
98-
98+
```Go
9999
slice:=[]int{1,2}
100100

101101
for _, v := range slice {
@@ -104,32 +104,32 @@ And we use the following code to validate the input:
104104
}
105105
}
106106
return false
107-
107+
```
108108
## Check boxes
109109

110110
Suppose there are some check boxes for user interests, and that you don't want extraneous values here either. You can validate these ase follows:
111-
111+
```html
112112
<input type="checkbox" name="interest" value="football">Football
113113
<input type="checkbox" name="interest" value="basketball">Basketball
114114
<input type="checkbox" name="interest" value="tennis">Tennis
115-
115+
```
116116
In this case, the sanitization is a little bit different to validating the button and check box inputs since here we get a slice from the check boxes.
117-
118-
slice:=[]string{"football","basketball","tennis"}
119-
a:=Slice_diff(r.Form["interest"],slice)
120-
if a == nil{
121-
return true
122-
}
123-
124-
return false
125-
117+
```Go
118+
slice:=[]string{"football","basketball","tennis"}
119+
a:=Slice_diff(r.Form["interest"],slice)
120+
if a == nil{
121+
return true
122+
}
123+
124+
return false
125+
```
126126
## Date and time
127127

128128
Suppose you want users to input valid dates or times. Go has the `time` package for converting year, month and day to their corresponding times. After that, it's easy to check it.
129-
129+
```Go
130130
t := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
131131
fmt.Printf("Go launched at %s\n", t.Local())
132-
132+
```
133133
After you have the time, you can use the `time` package for more operations, depending on your needs.
134134

135135
In this section, we've discussed some common methods of validating form data on the server side. I hope that you now understand more about data validation in Go, especially how to use regular expressions to your advantage.

0 commit comments

Comments
 (0)