Home  >  Article  >  Backend Development  >  golang reads request body

golang reads request body

PHPz
PHPzOriginal
2023-05-15 10:48:092223browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn