
本文详解 go 中 `net/http` 请求体(body)为空的原因及解决方案,重点区分 get 查询参数与 post 请求体的处理方式,并提供完整示例代码。
在 go 的 net/http 包中,http.Request.Body 仅包含请求原始报文体(body)的内容,例如 POST、PUT 等方法中通过 Content-Type: application/json 发送的 jsON 数据。而 GET 请求的查询参数(query String)并不在 Body 中——它们被编码在 URL 末尾(如 /step?steps=1&direction=1),因此调用 json.NewDecoder(req.Body).Decode(…) 在 GET 请求下必然失败:req.Body 为 nil 或已读尽,解码结果为
✅ 正确处理方式取决于请求方法
1. 对于 GET 请求(含 URL 查询参数)
应使用 req.ParseForm() 解析查询字符串,再通过 req.FormValue() 或 req.Form 获取值:
func stepHandler(res http.ResponseWriter, req *http.Request) { // 必须先调用 ParseForm —— 它会同时解析 query string 和表单 body(若存在) if err := req.ParseForm(); err != nil { http.Error(res, "Invalid form data", http.StatusbadRequest) return } steps := req.FormValue("steps") // string: "1" direction := req.FormValue("direction") // string: "1" cellsjson := req.FormValue("cells") // string: "[{"row":11,...}]" var cells []map[string]interface{} if err := json.Unmarshal([]byte(cellsJSON), &cells); err != nil { http.Error(res, "Invalid cells JSON", http.StatusBadRequest) return } log.Printf("Steps: %s, Direction: %s, Cells: %+v", steps, direction, cells) }
⚠️ 注意:req.ParseForm() 是幂等的,但必须在首次访问 req.Form 或 req.PostForm 前调用;对 GET 请求,它主要解析 req.URL.Query()。
2. 对于 POST 请求(发送 JSON Body)
需确保前端发送的是真正的 JSON 请求体,并设置正确 Header:
$.ajax({ url: "/step", method: "POST", contentType: "application/json", // 关键:声明 Content-Type data: JSON.stringify({ steps: parseInt($("#step-size").val()), direction: $("#step-forward").prop("checked") ? 1 : -1, cells: painted // 直接传数组,不再 stringify 外层 }), success: function(data) { painted = data; redraw(); } });
后端(接收 JSON Body):
func stepHandler(res http.ResponseWriter, req *http.Request) { if req.Method != "POST" { http.Error(res, "Method not allowed", http.StatusMethodNotAllowed) return } var payload struct { Steps int `json:"steps"` Direction int `json:"direction"` Cells []struct{ Row, Column int } `json:"cells"` } // Body 可被 json.Decoder 读取(注意:Body 只能读一次!) if err := json.NewDecoder(req.Body).Decode(&payload); err != nil { http.Error(res, "Invalid JSON in request body", http.StatusBadRequest) return } log.Printf("Received: %+v", payload) }
? 关键总结
- req.Body ≠ 查询参数:GET 参数在 URL 中,不在 Body;
- req.ParseForm() 是解析查询参数和 x-www-form-urlencoded 表单的统一入口;
- json.Decoder 仅适用于 Content-Type: application/json 的请求体,且 Body 必须未被读取过;
- 混合使用时(如 GET + query + POST + JSON),需按 HTTP 规范明确语义,避免混淆;
- 调试技巧:打印 req.Method、req.URL.String()、req.Header.Get(“Content-Type”) 和 req.ContentLength 可快速定位问题。
遵循上述原则,即可准确、健壮地处理各类 HTTP 请求参数。