Home > Article > Backend Development > Parse HTTP request body in Golang
There are three main ways to parse the HTTP request body in Go: Use io.ReadAll to read the entire body. Use json.Decoder to parse the JSON body. Use r.ParseMultipartForm to parse form data.
Parsing the HTTP request body in Golang
Parsing the HTTP request body is crucial for receiving data from the client and processing the request . Golang provides multiple methods to parse the request body, and this article will explore the most commonly used methods.
Parsing method
1. Use io.ReadAll
to read the entire text
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. Use json.Decoder
to parse JSON text
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. Use multipart/form-data
to parse form data
func parseFormData(w http.ResponseWriter, r *http.Request) { if err := r.ParseMultipartForm(32 << 20); err != nil { http.Error(w, "Could not parse form data", http.StatusBadRequest) return } // 访问表单字段 r.Form }
Practical Case
A simple REST API endpoint can handle JSON requests and return responses:
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) }
By using these methods, you can easily Parse the HTTP request body in Golang and receive the required data from the client.
The above is the detailed content of Parse HTTP request body in Golang. For more information, please follow other related articles on the PHP Chinese website!