在 Go (1.4) 中使用簡單的 HTTP 服務器,如果 content-type 設置為“application/json”,則請求表單為空。這是故意的嗎?簡單的 http 處理程序:func (s Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { r.ParseForm() log.Println(r.Form)}對于這個 curl 請求,處理程序打印正確的表單值:curl -d '{"foo":"bar"}' http://localhost:3000prints: map[foo:[bar]]對于此 curl 請求,處理程序不會打印表單值:curl -H "Content-Type: application/json" -d '{"foo":"bar"}' http://localhost:3000prints: map[]
1 回答

烙印99
TA貢獻1829條經驗 獲得超13個贊
ParseForm 不解析 JSON 請求正文。第一個示例的輸出出乎意料。
以下是解析 JSON 請求正文的方法:
func (s Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var v interface{}
err := json.NewDecoder(r.Body).Decode(&v)
if err != nil {
// handle error
}
log.Println(v)
}
您可以定義一個類型以匹配 JSON 文檔的結構并解碼為該類型:
func (s Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var v struct {
Foo string `json:"foo"`
}
err := json.NewDecoder(r.Body).Decode(&v)
if err != nil {
// handle error
}
log.Printf("%#v", v) // logs struct { Foo string "json:\"foo\"" }{Foo:"bar"} for your input
}
- 1 回答
- 0 關注
- 212 瀏覽
添加回答
舉報
0/150
提交
取消