本文详解 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 或已读尽,解码结果为
应使用 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("St
eps: %s, Direction: %s, Cells: %+v", steps, direction, cells)
}⚠️ 注意:req.ParseForm() 是幂等的,但必须在首次访问 req.Form 或 req.PostForm 前调用;对 GET 请求,它主要解析 req.URL.Query()。
需确保前端发送的是真正的 JSON 请求体,并设置正确 Header:
前端(AJAX 修改版):
$.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)
}遵循上述原则,即可准确、健壮地处理各类 HTTP 请求参数。