在 go 中解析 http 请求正文有三种主要方法:使用 io.readall 读取整个正文。使用 json.decoder 解析 json 正文。使用 r.parsemultipartform 解析表单数据。

在 Golang 中解析 HTTP 请求正文
解析 HTTP 请求正文对于从客户端接收数据和处理请求至关重要。Golang 提供了多种方法来解析请求正文,本文将探讨最常用的方法。
解析方式
1. 使用 io.ReadAll 读取整个正文
func readAll(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Could not read body", http.StatusBadRequest)
return
}
// 使用 body ...
}
2. 使用 json.Decoder 解析 JSON 正文
使用 uber-go/dig 在 Golang 中实现依赖注入——基于反射容器,提供 Provide/Invoke、dig.In/dig.Out 参数与结果对象,支持命名依赖等
type RequestBody struct {
Name string `json:"name"`
}
func decodeJSON(w http.ResponseWriter, r *http.Request) {
body := RequestBody{}
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&body)
if err != nil {
http.Error(w, "Could not decode JSON body", http.StatusBadRequest)
return
}
// 使用 body.Name ...
}
3. 使用 multipart/form-data 解析表单数据
func parseFormData(w http.ResponseWriter, r *http.Request) {
if err := r.ParseMultipartForm(32 <p><strong>实战案例</strong></p><p>一个简单的 REST API 端点可以处理 JSON 请求并返回响应:</p><pre class="brush:go;toolbar:false;">package main
import (
"encoding/json"
"fmt"
"net/http"
)
type RequestBody struct {
Name string `json:"name"`
}
func main() {
http.HandleFunc("/", handleRequest)
http.ListenAndServe(":8080", nil)
}
func handleRequest(w http.ResponseWriter, r *http.Request) {
// 解析 JSON 请求正文
body := RequestBody{}
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&body)
if err != nil {
http.Error(w, "Could not decode JSON body", http.StatusBadRequest)
return
}
// 处理请求...
// 返回响应
fmt.Fprintf(w, "Hello, %s!", body.Name)
}
通过使用这些方法,你可以轻松地解析 Golang 中的 HTTP 请求正文,并从客户端接收所需的数据。
golang免费学习笔记(深入):立即使用
在学习笔记中,你将探索golang的核心概念和高级技巧!










