go处理表单

1.处理表单输入

前端样例:

1
2
3
4
5
6
7
8
9
<!DOCTYPE html>
<body>
<form action="http://127.0.0.1:8080/login" method="post">
用户名:<input type="text" name="username">
密码:<input type="password" name="password">
<input type="submit" value="login">
</form>
</body>
</html>

后端样例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package main

import (
"fmt"
"log"
"net/http"
"text/template"
)

func main() {
http.HandleFunc("/login", login)
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal(err)
}
}

func login(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
t, err := template.ParseFiles("./login.html")
if err != nil {
log.Fatal(err)
}
t.Execute(w, nil)
} else {
// 这一步必不可少,否则获取不到表单数据。
r.ParseForm()
for k, v := range r.Form {
fmt.Println(k, "------", v)
}

fmt.Fprintf(w, "get login mesage.")
}
}

2.处理文件上传

前端样例:

1
2
3
4
5
6
7
8
9
<!DOCTYPE html>
<body>
<form action="http://127.0.0.1:8080/upload" method="post" enctype="multipart/form-data">
选择文件上传:<input type="file" name="upload">
<input type="hidden" name="token" value={{.}}>
<input type="submit" value="upload">
</form>
</body>
</html>

后端样例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package main

import (
"crypto/md5"
"fmt"
"io"
"log"
"net/http"
"os"
"text/template"
)

func main() {
http.HandleFunc("/upload", upload)
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal(err)
}
}

func upload(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
t, err := template.ParseFiles("./upload.html")
if err != nil {
log.Fatal(err)
}

h := md5.New()
token := fmt.Sprintf("%x", h.Sum(nil))
t.Execute(w, token)
} else {
// 读取上传文件的步骤
r.ParseMultipartForm(32 << 20)
f, fileHeader, err := r.FormFile("upload")

if err != nil {
log.Fatal(err)
}
defer f.Close()

fmt.Fprintf(w, "get upload file.")
// 在服务器端创建文件并保存
file, err := os.OpenFile("./"+fileHeader.Filename, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
log.Fatal(err)
}
defer file.Close()

io.Copy(file, f)
}
}