在 go 的 net/http 中,`req.body` 仅包含请求体(如 post/put 的原始数据),而 url 查询参数(get 参数)始终位于 url 中,需通过 `req.parseform()` 解析后从 `req.form` 或 `req.url.query()` 获取,直接读取 `req.body` 必然为空。
你遇到的 req.Body 始终为空、json.Decoder 解析失败并输出
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。
应改用 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)
}| 场景 | 数据位置 | 解析方式 |
|---|---|---|
| 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 语义。