Form:存储了post、put和get参数, 在使用之前需要调用ParseForm方法。
PostForm:存储了post、put参数, 在使用之前需要调用ParseForm方法。
MultipartForm:存储了包含了文件上传的表单的post参数, 在使用前需要调用ParseMultipartForm方法。
package main
import (
"fmt"
"io"
"io/ioutil"
"net/http"
)
//加载首页的页面
func indexHandler(w http.ResponseWriter, r *http.Request) {
data, err := ioutil.ReadFile("./static/index.html")
if err != nil {
io.WriteString(w, "internel server error")
return
}
io.WriteString(w, string(data))
//w.Write(data)
}
//接收表单参数
func userHandler(w http.ResponseWriter, r *http.Request) {
r.ParseForm() //解析参数,默认是不会解析的
if r.Method == "GET" { //GET请求的方法
username := r.Form.Get("username") //必须使用双引号, 注意: 这里的Get 不是指只接收GET请求的参数, 而是获取参数
password := r.Form.Get("password")
// limit, _ := strconv.Atoi(r.Form.Get("limit")) //字符串转整数的接收方法
//io.WriteString(w, username+":"+password)
w.Write([]byte(username + ":" + password))
} else if r.Method == "POST" { //POST请求的方法
username := r.Form.Get("username") //必须使用双引号, 注意: POST请求, 也是用Get方法来接收
password := r.Form.Get("password")
//io.WriteString(w, username+":"+password)
w.Write([]byte(username + ":" + password))
}
}
func main() {
// 静态资源处理
http.Handle("/static/",
http.StripPrefix("/static/",
http.FileServer(http.Dir("./static"))))
// 动态接口路由设置
http.HandleFunc("/index", indexHandler)
http.HandleFunc("/user", userHandler)
// 监听端口
fmt.Println("上传服务正在启动, 监听端口:8080...")
err := http.ListenAndServe(":8080", nil)
if err != nil {
fmt.Printf("Failed to start server, err:%s", err.Error())
}
}
static/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p>这是首页的内容</p>
</body>
</html>
D:\work\src>go run main.go
上传服务正在启动, 监听端口:8080...
访问方式:
http://localhost:8080/user?username=zhangsan&password=123456