diff --git a/en/04.1.md b/en/04.1.md
index a95ade6c..781105f6 100644
--- a/en/04.1.md
+++ b/en/04.1.md
@@ -1,71 +1,72 @@
# 4.1 Process form inputs
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.
-
-
+```html
+
-
+
-
-
+
+```
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.
This is easy to find out using the `http` package. Let's see how to handle the form data on the login page.
- package main
+```Go
+package main
- import (
- "fmt"
- "html/template"
- "log"
- "net/http"
- "strings"
- )
+import (
+ "fmt"
+ "html/template"
+ "log"
+ "net/http"
+ "strings"
+)
- func sayhelloName(w http.ResponseWriter, r *http.Request) {
- r.ParseForm() //Parse url parameters passed, then parse the response packet for the POST body (request body)
- // attention: If you do not call ParseForm method, the following data can not be obtained form
- fmt.Println(r.Form) // print information on server side.
- fmt.Println("path", r.URL.Path)
- fmt.Println("scheme", r.URL.Scheme)
- fmt.Println(r.Form["url_long"])
- for k, v := range r.Form {
- fmt.Println("key:", k)
- fmt.Println("val:", strings.Join(v, ""))
- }
- fmt.Fprintf(w, "Hello astaxie!") // write data to response
+func sayhelloName(w http.ResponseWriter, r *http.Request) {
+ r.ParseForm() //Parse url parameters passed, then parse the response packet for the POST body (request body)
+ // attention: If you do not call ParseForm method, the following data can not be obtained form
+ fmt.Println(r.Form) // print information on server side.
+ fmt.Println("path", r.URL.Path)
+ fmt.Println("scheme", r.URL.Scheme)
+ fmt.Println(r.Form["url_long"])
+ for k, v := range r.Form {
+ fmt.Println("key:", k)
+ fmt.Println("val:", strings.Join(v, ""))
}
+ fmt.Fprintf(w, "Hello astaxie!") // write data to response
+}
- func login(w http.ResponseWriter, r *http.Request) {
- fmt.Println("method:", r.Method) //get request method
- if r.Method == "GET" {
- t, _ := template.ParseFiles("login.gtpl")
- t.Execute(w, nil)
- } else {
- r.ParseForm()
- // logic part of log in
- fmt.Println("username:", r.Form["username"])
- fmt.Println("password:", r.Form["password"])
- }
+func login(w http.ResponseWriter, r *http.Request) {
+ fmt.Println("method:", r.Method) //get request method
+ if r.Method == "GET" {
+ t, _ := template.ParseFiles("login.gtpl")
+ t.Execute(w, nil)
+ } else {
+ r.ParseForm()
+ // logic part of log in
+ fmt.Println("username:", r.Form["username"])
+ fmt.Println("password:", r.Form["password"])
}
-
- func main() {
- http.HandleFunc("/", sayhelloName) // setting router rule
- http.HandleFunc("/login", login)
- err := http.ListenAndServe(":9090", nil) // setting listening port
- if err != nil {
- log.Fatal("ListenAndServe: ", err)
- }
+}
+
+func main() {
+ http.HandleFunc("/", sayhelloName) // setting router rule
+ http.HandleFunc("/login", login)
+ err := http.ListenAndServe(":9090", nil) // setting listening port
+ if err != nil {
+ log.Fatal("ListenAndServe: ", err)
}
+}
-
+```
Here we use `r.Method` to get the request method, and it returns an http verb -"GET", "POST", "PUT", etc.
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
Figure 4.2 Server prints request data
The type of `request.Form` is `url.Value`. It saves data with the format `key=value`.
-
+```Go
v := url.Values{}
v.Set("name", "Ava")
v.Add("friend", "Jess")
@@ -97,7 +98,7 @@ The type of `request.Form` is `url.Value`. It saves data with the format `key=va
fmt.Println(v.Get("name"))
fmt.Println(v.Get("friend"))
fmt.Println(v["friend"])
-
+```
**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.
## Links
diff --git a/en/04.2.md b/en/04.2.md
index 08fabec9..8456c842 100644
--- a/en/04.2.md
+++ b/en/04.2.md
@@ -7,17 +7,17 @@ There are two ways of verifying form data that are in common use. The first is J
## Required fields
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.
-
+```Go
if len(r.Form["username"][0])==0{
// code for empty field
}
-
+```
`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.
## Numbers
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.
-
+```Go
getint,err:=strconv.Atoi(r.Form.Get("age"))
if err!=nil{
// 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
if getint >100 {
// too big
}
-
+```
Another way to do this is by using regular expressions.
-
+```Go
if m, _ := regexp.MatchString("^[0-9]+$", r.Form.Get("age")); !m {
return false
}
-
+```
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.
## Chinese
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.
-
- if m, _ := regexp.MatchString("^[\\x{4e00}-\\x{9fa5}]+$", r.Form.Get("realname")); !m {
- return false
- }
-
+```Go
+if m, _ := regexp.MatchString("^[\\x{4e00}-\\x{9fa5}]+$", r.Form.Get("realname")); !m {
+ return false
+}
+```
## English letters
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.
-
- if m, _ := regexp.MatchString("^[a-zA-Z]+$", r.Form.Get("engname")); !m {
- return false
- }
-
+```Go
+if m, _ := regexp.MatchString("^[a-zA-Z]+$", r.Form.Get("engname")); !m {
+ return false
+}
+```
## E-mail address
If you want to know whether users have entered valid E-mail addresses, you can use the following regular expression:
-
+```Go
if m, _ := regexp.MatchString(`^([\w\.\_]{2,10})@(\w{1,}).([a-z]{2,4})$`, r.Form.Get("email")); !m {
fmt.Println("no")
}else{
fmt.Println("yes")
}
-
+```
## Drop down list
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?
Suppose we have the following `