When using Golang for web development, sometimes it is necessary to read the body part of the HTTP request (such as the submission data carried in the POST request) for processing. This article will introduce how Golang reads the body of an HTTP request.
1. Use ioutil.ReadAll() to read
The ioutil package in the Golang standard library provides a ReadAll() function that can read all objects in any io.Reader type data, and returns data of type []byte. Therefore, we can read the body part of the HTTP request by passing the http.Request.Body field as a parameter to the ReadAll() function. The sample code is as follows:
package main import ( "fmt" "io/ioutil" "net/http" ) func handler(w http.ResponseWriter, r *http.Request) { body, err := ioutil.ReadAll(r.Body) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } defer r.Body.Close() // 处理body数据 fmt.Fprint(w, string(body)) } func main() { http.HandleFunc("/", handler) http.ListenAndServe(":8080", nil) }
In the above sample code, we define an HTTP request processing function handler(), in which the body part of the HTTP request is read and converted into a string type. Output to the HTTP response.
It should be noted that when using the ioutil.ReadAll() function to read the body of an HTTP request, the http.Request.Body field should be closed after the function returns to release resources. The defer statement is used here to ensure that the field is closed after the function is executed.
2. Use json.Decoder to read JSON data
If the body part of the HTTP request is data in JSON format, we can use the json.Decoder type in Golang to directly read the JSON data And parsed into Golang's data structure. The sample code is as follows:
package main import ( "encoding/json" "fmt" "net/http" ) type User struct { Username string `json:"username"` Password string `json:"password"` } func handler(w http.ResponseWriter, r *http.Request) { var user User err := json.NewDecoder(r.Body).Decode(&user) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } defer r.Body.Close() // 处理user对象 fmt.Fprintf(w, "Username: %s, Password: %s", user.Username, user.Password) } func main() { http.HandleFunc("/", handler) http.ListenAndServe(":8080", nil) }
In the above sample code, we defined a structure type named User and created a json.Decoder type using the json.NewDecoder() function in the HTTP request processing function Object, and then use its Decode() method to directly parse the body part of the HTTP request into User type data and process it.
It should be noted that when using json.Decoder to read the body of an HTTP request, the http.Request.Body field should be closed before the function returns to release resources. Moreover, you need to pass a pointer to the target structure type as a parameter of the Decode() method (for example, &user) so that the parsed JSON data can be filled into the structure object.
3. Use xml.Decoder to read XML data
If the body part of the HTTP request is data in XML format, we can similarly use the xml.Decoder type in Golang to read it directly XML data and parsed into Golang data structures. The sample code is as follows:
package main import ( "encoding/xml" "fmt" "net/http" ) type User struct { XMLName xml.Name `xml:"user"` Username string `xml:"username"` Password string `xml:"password"` } func handler(w http.ResponseWriter, r *http.Request) { var user User err := xml.NewDecoder(r.Body).Decode(&user) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } defer r.Body.Close() // 处理user对象 fmt.Fprintf(w, "Username: %s, Password: %s", user.Username, user.Password) } func main() { http.HandleFunc("/", handler) http.ListenAndServe(":8080", nil) }
In the above sample code, we defined a structure type named User and created an xml.Decoder type using the xml.NewDecoder() function in the HTTP request processing function. Object, and then use its Decode() method to directly parse the body part of the HTTP request into User type data and process it.
It should be noted that when using xml.Decoder to read the body of an HTTP request, the http.Request.Body field should be closed before the function returns to release resources. Furthermore, you need to specify the name of the corresponding XML node for each field in the target structure type (for example, the XML node corresponding to the Username field is username).
Summary
This article introduces how Golang reads the body of an HTTP request. By using the ioutil package, json.Decoder type and xml.Decoder type in the standard library, we can easily read and parse the body part of the HTTP request into Golang's data structure for processing.
The above is the detailed content of golang reads request body. For more information, please follow other related articles on the PHP Chinese website!

The article explains how to use the pprof tool for analyzing Go performance, including enabling profiling, collecting data, and identifying common bottlenecks like CPU and memory issues.Character count: 159

The article discusses writing unit tests in Go, covering best practices, mocking techniques, and tools for efficient test management.

This article demonstrates creating mocks and stubs in Go for unit testing. It emphasizes using interfaces, provides examples of mock implementations, and discusses best practices like keeping mocks focused and using assertion libraries. The articl

This article explores Go's custom type constraints for generics. It details how interfaces define minimum type requirements for generic functions, improving type safety and code reusability. The article also discusses limitations and best practices

The article discusses Go's reflect package, used for runtime manipulation of code, beneficial for serialization, generic programming, and more. It warns of performance costs like slower execution and higher memory use, advising judicious use and best

The article discusses using table-driven tests in Go, a method that uses a table of test cases to test functions with multiple inputs and outcomes. It highlights benefits like improved readability, reduced duplication, scalability, consistency, and a

This article explores using tracing tools to analyze Go application execution flow. It discusses manual and automatic instrumentation techniques, comparing tools like Jaeger, Zipkin, and OpenTelemetry, and highlighting effective data visualization

The article discusses managing Go module dependencies via go.mod, covering specification, updates, and conflict resolution. It emphasizes best practices like semantic versioning and regular updates.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.
