我正在嘗試獲取 POST 請(qǐng)求中的參數(shù),但我無(wú)法做到,我的代碼是: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.") }}我正在終端中發(fā)出 POST 請(qǐng)求,如下所示:curl -X POST -d '{"name":"Alex","age":"50"}' localhost:8080然后輸出是:This have been received:name: age: 為什么它不采用參數(shù)?我做錯(cuò)了什么?
1 回答

慕容3067478
TA貢獻(xiàn)1773條經(jīng)驗(yàn) 獲得超3個(gè)贊
當(dāng)您將 body 作為json對(duì)象傳遞時(shí),您最好定義一個(gè)Go與該對(duì)象匹配的結(jié)構(gòu)并將 body 解碼request為對(duì)象。
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
這個(gè)POST請(qǐng)求現(xiàn)在工作正常。
您可以根據(jù)需要修改Go結(jié)構(gòu)和響應(yīng)object。
- 1 回答
- 0 關(guān)注
- 258 瀏覽
添加回答
舉報(bào)
0/150
提交
取消