答案:Go通过net/http库处理HTTP POST请求。服务端使用http.HandleFunc解析表单或JSON数据,客户端用http.Post发送数据,需注意方法校验、Content-Type检查、请求体读取与响应关闭。

在Golang中处理HTTP POST请求,主要依赖标准库net/http。无论是作为客户端发送POST请求,还是作为服务端接收并解析POST数据,Go都提供了简洁高效的实现方式。
作为服务端:接收并解析POST请求
编写一个HTTP服务端来处理POST请求时,需要注册路由并使用http.HandleFunc或http.Handler来定义处理函数。
常见场景包括接收表单数据、JSON数据等。以下是一个完整示例:
func handlePost(w http.ResponseWriter, r *http.Request) {if r.Method != "POST" {
http.Error(w, "仅支持POST方法", http.StatusMethodNotAllowed)
return
}
// 解析表单数据(包括application/x-www-form-urlencoded)
r.ParseForm()
name := r.FormValue("name")
email := r.FormValue("email")
fmt.Fprintf(w, "接收到数据: 名称=%s, 邮箱=%s\n", name, email)
}
func main() {
http.HandleFunc("/post-form", handlePost)
log.Fatal(http.ListenAndServe(":8080", nil))
}
如果前端发送的是JSON数据,需要手动读取请求体并解码:
立即学习“go语言免费学习笔记(深入)”;
Name string `json:"name"`
Email string `json:"email"`
}
func handleJSON(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Content-Type") != "application/json" {
http.Error(w, "Content-Type必须为application/json", http.StatusBadRequest)
return
}
var user User
body, _ := io.ReadAll(r.Body)
if err := json.Unmarshal(body, &user); err != nil {
http.Error(w, "无效的JSON", http.StatusBadRequest)
return
}
fmt.Fprintf(w, "JSON数据: %+v", user)
}
作为客户端:发送POST请求
使用http.Post或http.PostForm可以轻松发送POST请求。
发送表单数据:
resp, err := http.PostForm("https://httpbin.org/post", url.Values{"name": {"张三"},
"email": {"zhangsan@example.com"},
})
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
发送JSON数据:
user := User{Name: "李四", Email: "lisi@example.com"}jsonData, _ := json.Marshal(user)
resp, err := http.Post("https://httpbin.org/post", "application/json",
bytes.NewBuffer(jsonData))
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
常见注意事项
处理POST请求时,有几个关键点需要注意:
- 始终检查请求方法是否为POST,避免误处理GET等其他方法
- 对于JSON请求,验证
Content-Type头有助于提前发现错误 - 记得调用
ParseForm()才能访问FormValue - 请求体只能读取一次,多次读取需通过
io.TeeReader缓存 - 客户端发送请求后要记得关闭响应体
resp.Body.Close()










