我正在嘗試獲取 POST 請求中的參數,但我無法做到,我的代碼是:package mainimport ( "fmt" "log" "net/http")func main() { http.HandleFunc("/", hello) fmt.Printf("Starting server for testing HTTP POST...\n") if err := http.ListenAndServe(":8080", nil); err != nil { log.Fatal(err) }}func hello(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/" { http.Error(w, "404 not found.", http.StatusNotFound) return } switch r.Method { case "POST": // Call ParseForm() to parse the raw query and update r.PostForm and r.Form. if err := r.ParseForm(); err != nil { fmt.Fprintf(w, "ParseForm() err: %v", err) return } name := r.Form.Get("name") age := r.Form.Get("age") fmt.Print("This have been received:") fmt.Print("name: ", name) fmt.Print("age: ", age) default: fmt.Fprintf(w, "Sorry, only POST methods are supported.") }}我正在終端中發出 POST 請求,如下所示:curl -X POST -d '{"name":"Alex","age":"50"}' localhost:8080然后輸出是:This have been received:name: age: 為什么它不采用參數?我做錯了什么?
1 回答

慕容3067478
TA貢獻1773條經驗 獲得超3個贊
當您將 body 作為json對象傳遞時,您最好定義一個Go與該對象匹配的結構并將 body 解碼request為對象。
type Info struct {
Name string
Age int
}
info := &Info{}
if err := json.NewDecoder(r.Body).Decode(info); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
_ = json.NewEncoder(w).Encode(info)
您可以在此處找到完整的工作代碼。
$ curl -X POST -d '{"name":"Alex","age":50}' localhost:8080
這個POST請求現在工作正常。
您可以根據需要修改Go結構和響應object。
- 1 回答
- 0 關注
- 261 瀏覽
添加回答
舉報
0/150
提交
取消