我開(kāi)始瘋狂地試圖讓 Go 解碼這個(gè) json 請(qǐng)求正文。這是一個(gè)示例請(qǐng)求: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:}})就像評(píng)論所暗示的那樣,我可以驗(yàn)證這req.Body確實(shí)是正確的——但無(wú)論出于何種原因,json.NewDecoder(req.Body).Decode(&body)永遠(yuǎn)不會(huì)填寫body.任何幫助將不勝感激!
JSON 解碼器不適用于 http 請(qǐng)求正文
開(kāi)滿天機(jī)
2021-09-13 19:56:26