Request parameter processing of Golang Gin framework

How to obtain the data in the request through various methods in Gin. Gin obtains route parameters through the c.Param() method, which are variables defined in the route. For example:

r.GET("/user/:id", func(c *gin.Context) {
    id := c.Param("id")
    c.String(http.StatusOK, "id=%s", id)
})

But if you need to get multiple parameters, you can use the c.Params property, which is an array that contains all parameters. For example: GET and POST of gin framework to obtain parameters

r.GET("/user/:id/:name", func(c *gin.Context) {
    id := c.Param("id")
    name := c.Param("name")
    params := c.Params
    c.String(http.StatusOK, "id=%s, name=%s, params=%v", id, name, params)
})

A route /user/:id/:name is defined here, and the values of all parameters can be obtained through the c.Params method. It should be noted that the c.Params method returns an array, where each element is a gin.Param structure, which contains the key-value pair information of the parameters. The key and value can be obtained through the Key and Value properties respectively.

Get various request parameters

In addition to routing parameters, in the Gin framework, you can use c.Query(), c.DefaultQuery(), c.PostForm(), c.DefaultPostForm() and other methods to obtain the parameters submitted by the client. These methods work for both GET and POST requests.

For example, use the c.Query() method to get the parameters submitted by the client through the URL:

r.GET("/user", func(c *gin.Context) {
    name := c.Query("name")
    age := c.Query("age")
    c.String(http.StatusOK, "name=%s, age=%s", name, age)
})

The c.Query() method is used here to obtain the name and age parameters submitted by the client.

Use the c.DefaultQuery() method to obtain the parameters submitted by the client and set a default value if the parameter does not exist:

//Source public account: [Advanced Notes on Programming for Coders] r.GET("/user", func(c *gin.Context) { name := c.DefaultQuery("name", "guest")
    age := c.DefaultQuery("age", "0")
    c.String(http.StatusOK, "name=%s, age=%s", name, age)
})

The c.DefaultQuery() method is used here to obtain the name and age parameters submitted by the client. If these parameters do not exist, default values are set.

Similarly, use the c.PostForm() and c.DefaultPostForm() methods to obtain parameters submitted by the client via a POST request. For example: GET and POST of gin framework to obtain parameters

r.POST("/user", func(c *gin.Context) {
    name := c.PostForm("name")
    age := c.PostForm("age")
    c.String(http.StatusOK, "name=%s, age=%s", name, age)
})

The c.PostForm() method is used here to obtain the name and age parameters submitted by the client.

It should be noted that when using the c.PostForm() and c.DefaultPostForm() methods to obtain client POST request parameters, the c.Request.ParseForm() method needs to be called before processing the request in order to parse the form parameters. For example: Go Programmer Interview Written Test Guide – Arrays and Slices

r.POST("/user", func(c *gin.Context) {
    c.Request.ParseForm()
    name := c.PostForm("name")
    age := c.PostForm("age")
    c.String(http.StatusOK, "name=%s, age=%s", name, age)
})

In addition, the Gin framework also supports binding parameters submitted by the client into a structure through methods such as c.Bind(), c.ShouldBind(), c.ShouldBindJSON(), c.ShouldBindXML(), etc. These methods will automatically parse the request body and bind the parameters to the specified structure. For example:

type User struct {
    Name string `form:"name" json:"name" xml:"name"`
    Age int `form:"age" json:"age" xml:"age"`
}

r.POST("/user", func(c *gin.Context) {
    var userUser
    c.Bind(&user)
    c.String(http.StatusOK, "name=%s, age=%d", user.Name, user.Age)
})

A User structure is defined here, and the c.Bind() method is used to bind the parameters submitted by the client to the structure, and then use the structure to process the request. Use form, json, xml and other tags in the structure to specify parameter names so that the parameters can be bound correctly. Source public account: [Advanced Notes on Programming for Coders]

Special instructions for JSON request processing

Use the c.ShouldBindJSON() method to handle JSON requests submitted by the client. This method can bind JSON data to a specified structure. The example is as follows:

type User struct {
    Name string `json:"name"`
    Email string `json:"email"`
}

func main() {
    r := gin.Default()
    r.POST("/user", func(c *gin.Context) {
        var userUser
        
        if err := c.ShouldBindJSON( & amp;user); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
            return
        }
        
        c.JSON(http.StatusOK, gin.H{"name": user.Name, "email": user.Email})
    })
    
    r.Run(":8080")
}

In the above code, a User structure is first defined to store the JSON data submitted by the client. Then, the c.ShouldBindJSON() method is called in the route processing function to bind the JSON data submitted by the client to the user variable.

If the binding fails, an error message is returned. If the binding is successful, a JSON response is returned, returning the values of the name and email fields to the client.

It should be noted that when processing a JSON request, the data in the request body must be read completely before binding. Therefore, before calling the ShouldBindJSON() method, you need to ensure that the request body has been completely read. If the request body has not been read completely, this method will return an error message. Golang common test questions analysis (1)

In addition to the above methods, you can also use the c.BindJSON() method to process JSON requests. The example is as follows:

func main() {
    r := gin.Default()

    r.POST("/user", func(c *gin.Context) {
        var userUser

        if err := c.BindJSON( & amp;user); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
            return
        }

        c.JSON(http.StatusOK, gin.H{"name": user.Name, "email": user.Email})
    })

    r.Run(":8080")
}

The difference between the BindJSON() method and the ShouldBindJSON() method is that the BindJSON() method automatically determines the type of the request body based on the Content-Type field in the request header. If the request body type is not JSON, an error message will be returned. The ShouldBindJSON() method will only handle the case where the request body is JSON.

It should be noted that when using the BindJSON() method to process a JSON request, if the request body is not in JSON format, or the data in the request body cannot be bound to the specified structure, this method will also return an error message. Therefore, when using the BindJSON() method, you need to ensure that the data in the request body is legal. Get started in one minute and make database operation with Golang a pleasure

Processing of various data formats

In addition to the above methods, you can also use the c.ShouldBind() method to process request data in any format, including JSON, XML, Form and other formats. This method will automatically identify the requested data format based on the Content-Type field in the request header and bind the data to the specified structure. Examples are as follows:

//Source public account: [Advanced Notes on Programming for Coders] func main() { r := gin.Default()

    r.POST("/user", func(c *gin.Context) {
        var userUser

        if err := c.ShouldBind( & amp;user); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
            return
        }

        c.JSON(http.StatusOK, gin.H{"name": user.Name, "email": user.Email})
    })

    r.Run(":8080")
}

In the above code, the c.ShouldBind() method is called to bind the data submitted by the client to the user variable. If the binding fails, an error message is returned. If the binding is successful, a JSON response is returned, returning the values of the name and email fields to the client.

It should be noted that when using the ShouldBind() method to process request data, you need to ensure that the data in the request body is legal. Otherwise, this method will also return an error message. Go language dependency management three-factor example analysis guide

Others

In addition to the above methods, the Gin framework also provides some other methods to handle parameters submitted by the client, such as:

  • ? c.GetHeader(): Get the request header information submitted by the client.

  • ? c.GetRawData(): Get the request body information (raw data) submitted by the client.

  • ? c.Request.FormValue(): Get the form parameter value submitted by the client.

  • ? c.Request.PostFormValue(): Get the POST request parameter value submitted by the client.

The above methods are relatively flexible to use, and you can choose the appropriate method according to the specific scenario.

3a3bae18bf10c22a513ecc98e2dfc312.jpeg