GET请求:http://localhost:8089/get?id=1 服务端打印出以下内容 method: GET id1: 1 id2: 1 服务端返回 ok 字符串 GET请求(不带请求参数):http://localhost:8089/get 服务端打印出以下内容 method: GET id2: 服务端返回 ok 字符串
二、POST请求处理
json 处理:处理请求提交的方法有很多,下面简单的使用 json.NewDecoder 和 ioutil.ReadAll
请求示例:
POST http://localhost:8089/post
{
"username":"xiaoming"
}
json.NewDecoder 解析
// 结构体解析
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]
ioutil.ReadAll 读取
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"
}
form-data 处理:
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
PUT、PATH、DELETE的请求可以参考上面的 GET 和 POST 的方式。