【发布时间】:2021-01-12 19:58:06
【问题描述】:
我正在尝试获取 POST 请求中的参数,但我无法做到,我的代码是:
package main
import (
"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:
为什么不带参数?我做错了什么?
【问题讨论】:
-
您需要先执行
r.ParseForm(),它会解析来自 URL 的原始查询并填充表单。 -
A 正在这样做,在 case: POST 之后,在 if 条件中
-
您正在发送带有 json 数据的 POST。设置
Content-Type标头,使用json.Decode解析go中的数据。 -
或者您可以将 curl 命令更改为以 urlencoded 形式发布,以匹配代码的预期: curl -X POST -d name=Alex -d age=50 localhost:8080
-
这能回答你的问题吗? Handling JSON Post Request in Go