
在 go 的 net/http 中,`req.body` 仅包含请求体(如 post/put 的原始数据),而 url 查询参数(get 参数)始终位于 url 中,需通过 `req.parseform()` 解析后从 `req.form` 或 `req.url.query()` 获取,直接读取 `req.body` 必然为空。
你遇到的 req.Body 始终为空、json.Decoder 解析失败并输出
✅ 正确做法:区分请求类型,按需解析
1. 若坚持使用 GET(推荐用于简单参数)
URL 查询参数应通过 req.URL.Query() 或 req.FormValue() 获取,无需且不能用 json.Decoder 读 Body:
func stepHandler(res http.ResponseWriter, req *http.Request) { // ✅ 正确:解析 URL 查询参数 if err := req.ParseForm(); err != nil { http.Error(res, "Invalid query", http.StatusbadRequest) return } steps := req.FormValue("steps") // "1" direction := req.FormValue("direction") // "1" cellsjsON := req.FormValue("cells") // "[{"row":11,"column":15},...]" // 解析 json 字符串字段(如 cells) 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() 是安全的幂等操作,对 GET/POST 均有效;对 GET 请求,它会自动解析 req.URL.RawQuery。
2. 若需传输结构化 JSON(更规范的做法)
应改用 POST 请求 + Content-Type: application/json,此时参数才真正存在于 req.Body 中:
✅ 客户端(ajax)改为:
$.ajax({ url: "/step", method: "POST", contentType: "application/json", data: JSON.stringify({ steps: parseInt($("#step-size").val()), direction: $("#step-forward").prop("checked") ? 1 : -1, cells: painted // 直接传数组,无需额外 stringify }), success: function(data) { /* ... */ } });
✅ 服务端(接收 JSON Body):
func stepHandler(res http.ResponseWriter, req *http.Request) { if req.Method != "POST" { http.Error(res, "Method not allowed", http.StatusMethodNotAllowed) return } // ✅ 此时 req.Body 才有内容 defer req.Body.Close() var payload struct { Steps int `json:"steps"` Direction int `json:"direction"` Cells []struct{ Row, Column int } `json:"cells"` } if err := json.NewDecoder(req.Body).Decode(&payload); err != nil { http.Error(res, "Invalid JSON", http.StatusBadRequest) return } log.Printf("Steps: %d, Direction: %d, Cells: %+v", payload.Steps, payload.Direction, payload.Cells) }
⚠️ 关键注意事项
- req.Body 不会自动包含查询参数,无论 GET 还是 POST —— 查询参数永远属于 URL,请求体只属于 POST/PUT/PATCH 等方法的 payload。
- req.ParseForm() 必须在首次访问 req.Form 或 req.PostForm 前调用(go 1.19+ 已自动惰性调用,但仍建议显式调用以明确意图)。
- 对 req.Body 操作后(如 ioutil.ReadAll 或 json.Decoder.Decode),Body 流会被消耗完毕,不可重复读取;如需多次使用,请先 io.copy(ioutil.Discard, req.Body) 并用 bytes.NewReader(buf) 重建。
- 使用 req.URL.Query() 可避免 ParseForm() 的副作用(如对 POST 表单的解析),更适合纯 GET 场景。
✅ 总结
| 场景 | 数据位置 | 解析方式 |
|---|---|---|
| GET 查询参数(?a=1&b=2) | req.URL.RawQuery | req.URL.Query() 或 req.FormValue() |
| POST 表单(application/x-www-form-urlencoded) | req.Body | req.ParseForm() → req.PostForm |
| POST JSON(application/json) | req.Body | json.NewDecoder(req.Body).Decode() |
选择合适的方式,才能让 Go 的 HTTP 处理既健壮又符合 REST 语义。