func main() {
http.HandleFunc("/post", postHandler)
http.HandleFunc("/get", getHandler)
http.ListenAndServe(":8089", nil)
}
一、GET请求处理
func getHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println("method:", r.Method)
q := r.URL.Query()
if len(q) != 0 {
// 方式1:通过字典下标取值
fmt.Println("id1:", q["id"][0])
}
// 方式2:使用Get方法,如果没有值会返回空字符串
fmt.Println("id2:", q.Get("id"))
w.Write([]byte("ok"))
}
GET请求:http://localhost:8089/get?id=1
服务端打印出以下内容
method: GET
id1: 1
id2: 1
服务端返回 ok 字符串
GET请求(不带请求参数):http://localhost:8089/get
服务端打印出以下内容
method: GET
id2:
服务端返回 ok 字符串
POST http://localhost:8089/post
{
"username":"xiaoming"
}
// 结构体解析
func postHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println("method:", r.Method) // method: POST
param := &struct {
Username string `json:"username"`
}{}
// 通过json解析器解析参数
json.NewDecoder(r.Body).Decode(param)
fmt.Println(fmt.Sprintf("%#v", param))
// &struct { Username string "json:\"username\"" }{Username:"xiaoming"}
w.Write([]byte("ok"))
}
服务端打印内容:
method: POST
&struct { Username string "json:\"username\"" }{Username:"xiaoming"}
// map解析
func postHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println("method:", r.Method) // method: POST
var m map[string]interface{}
json.NewDecoder(r.Body).Decode(&m)
fmt.Println(m) // map[username:xiaoming]
w.Write([]byte("ok"))
}
服务端打印内容:
method: POST
map[username:xiaoming]
func postHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println("method:", r.Method)
b, _ := ioutil.ReadAll(r.Body)
fmt.Println("len(b):", len(b), "cap(b):", cap(b))
fmt.Println("body:", string(b))
w.Write([]byte("ok"))
}
服务端打印内容:
method: POST
len(b): 31 cap(b): 512
body: {
"username":"xiaoming"
}
POST http://localhost:8089/post
fmt.Println("val:", r.PostFormValue("username"))
fmt.Println("val2:", r.FormValue("username"))
// 读取文件
//r.FormFile("file")
服务端打印内容:
method: POST
val: xiaoyan
val2: xiaoyan