我開始瘋狂地試圖讓 Go 解碼這個 json 請求正文。這是一個示例請求:curl -X POST -d "{\"username\":\"foo\", \"password\":\"bar\"}" http://localhost:3000/users這是我的處理程序:mux.HandleFunc("/users", func(rw http.ResponseWriter, req *http.Request) { var body struct { username string password string } // buf := make([]byte, req.ContentLength) // req.Body.Read(buf) // fmt.Println(string(buf)) // // The above commented out code will correctly print: // {"username":"foo", "password":"bar"} err := json.NewDecoder(req.Body).Decode(&body) if err != nil { rw.WriteHeader(http.StatusNotAcceptable) return } fmt.Printf("%+v\n", body) // prints -> {username: password:}})就像評論所暗示的那樣,我可以驗證這req.Body確實是正確的——但無論出于何種原因,json.NewDecoder(req.Body).Decode(&body)永遠不會填寫body.任何幫助將不勝感激!
- 1 回答
- 0 關注
- 200 瀏覽
添加回答
舉報
0/150
提交
取消