1, Get query parameters
Query refers to the URL? Parameters carried later, such as user/info?username = Zhang San & password = 123. The method to obtain the requested query parameters is as follows:
- When using DefaultQuery, if the username entered by the browser is not obtained, the default value will be returned
username := ctx.DefaultQuery("username", "Jacko's tech grocery store")
- When using Query, if the password entered by the browser is not obtained, the "" empty string will be returned by default
password := ctx.Query("password")
A complete example is as follows
Browser input is:
http://127.0.0.1:8000/user/info?username = Zhang San & password = 123456
The server returns:
{"message":"success","password":"123456","username":"Zhang San"}
The back-end processing logic is as follows:
package main import ( "github.com/gin-gonic/gin" "net/http" ) func main() { //Set gin mode gin.SetMode(gin.ReleaseMode) //Create a new routing engine r := gin.New() // GET: request method/ user/info: requested path r.GET("/user/info", func(ctx *gin.Context) { // When using DefaultQuery, if the user name entered by the browser is not obtained, the default value is returned to the user name username := ctx.DefaultQuery("username", "Jacko's tech grocery store") // When using Query, if the password entered by the browser is not obtained, the "" empty string will be returned by default password := ctx.Query("password") // Return json to browser ctx.JSON(http.StatusOK, gin.H{ "message": "success", "username": username, "password": password, }) }) // Start the HTTP service. By default, the service is started at port 8080. It can also be set to other ports, such as 8000 r.Run(":8000") }
Note: Query method is generally used
2, Get form parameters
When the data requested by the front end is submitted through the form, for example, send a POST request to / user/info. The way to obtain the requested data is as follows:
A complete example is as follows
The back-end processing logic is as follows:
package main import ( "github.com/gin-gonic/gin" "net/http" ) func main() { //Set gin mode gin.SetMode(gin.ReleaseMode) //Create a new routing engine r := gin.New() // POST: request mode/ user/info: requested path r.POST("/user/info", func(ctx *gin.Context) { //When submitting single form data //If the form parameters are not obtained in the request, the default value "Zhang San" will be returned username := ctx.DefaultPostForm("username", "Zhang San") //If the form parameter is not obtained in the request, an empty string is returned password := ctx.PostForm("password") //When submitting multiple data in the checkbox info := ctx.PostFormArray("info") // Output json result to caller ctx.JSON(http.StatusOK, gin.H{ "message": "success", "username": username, "password": password, "info": info, }) }) // Start the HTTP service. By default, the service is started at port 8080. It can also be set to other ports, such as 8000 r.Run(":8000") }
Note: the PostForm method is generally used
3, Get JSON parameters
When the data requested by the front end is submitted through json, for example, send a POST request to / user/info, the way to obtain the request parameters is as follows:
- Configure json requests using postman as follows:
- The back-end processing logic is as follows:
package main import ( "github.com/gin-gonic/gin" "net/http" ) type User struct { // If you want to specify the returned json as another alias, you can use ` json:"username" to define the alias in json format UserName string `json:"username"` PassWord string `json:"password"` } func main() { //Set gin mode gin.SetMode(gin.ReleaseMode) //Create a new routing engine r := gin.New() // POST: request mode/ user/info: requested path r.POST("/user/info", func(ctx *gin.Context) { // Create a json structure instance and bind it to the request json parameter userBody := &User{} err := ctx.BindJSON(&userBody) // Judge whether the json request data structure is successfully bound to the defined structure if err != nil { ctx.JSON(200, gin.H{ "err_no": 400, "message": "Post Data Err", }) } else { ctx.JSON(http.StatusOK, gin.H{ "username": userBody.UserName, "password": userBody.PassWord, }) } }) // Start the HTTP service. By default, the service is started at port 8080. It can also be set to other ports, such as 8000 r.Run(":8080") }
- The returned results are as follows:
4, Get path parameter
The requested parameters are passed through the URL path, such as / user/info / Zhang San / 123456. The way to get the parameters in the request URL path is as follows.
- Browser input is:
127.0.0.1:8080/user/info/Zhang San/123456
- The back-end processing logic is as follows:
package main import ( "github.com/gin-gonic/gin" "net/http" ) func main() { //Set gin mode gin.SetMode(gin.ReleaseMode) //Create a new routing engine r := gin.New() // GET: request method/ user/info: requested path r.GET("/user/info/:username/:password", func(ctx *gin.Context) { // If the relevant path parameters are not obtained, the empty string "" is returned username := ctx.Param("username") password := ctx.Param("password") //Returns the result to the caller ctx.JSON(http.StatusOK, gin.H{ "message": "success", "username": username, "password": password, }) }) // Start the HTTP service. By default, the service is started at port 8080. It can also be set to other ports, such as 8000 r.Run(":8080") }
- The returned results are as follows:
{"message":"success","password":"123456","username":"Zhang San"}
Note that the following request route definition method is illegal. If you want to define two similar request routes, you can add a version number to distinguish them, such as / user/v1/info / - > / user / V2 / Info /, and the version number is from v1 to v2.
Incorrect writing:
// GET: request method/ hello: requested path r.GET("/user/info/:username/:password", func(c *gin.Context) { }) r.GET("/user/info/:username/:password", func(c *gin.Context) { })
Correct writing:
r.GET("/user/v1/info/:username/:password", func(ctx *gin.Context) { // If the relevant path parameters are not obtained, the empty string "" is returned username := ctx.Param("username") password := ctx.Param("password") //Returns the result to the caller ctx.JSON(http.StatusOK, gin.H{ "message": "success", "username": username, "password": password, }) }) r.GET("/user/v2/info/:username/:address", func(ctx *gin.Context) { // If the relevant path parameters are not obtained, the empty string "" is returned username := ctx.Param("username") address := ctx.Param("address") //Returns the result to the caller ctx.JSON(http.StatusOK, gin.H{ "message": "success", "username": username, "address": address, }) })
5, Parameter binding
In order to obtain the request related parameters more conveniently and improve the development efficiency, we can identify the request data type based on the content type of the request, and use the reflection mechanism to automatically extract the QueryString, form, JSON, XML and other parameters in the request into the structure. The following example code demonstrates ShouldBind() is a powerful function. It can automatically extract JSON, form and QueryString data based on the request, and bind the value to the specified structure object.
-
Request through query. Enter the url at this time. No other configuration is required:
-
Request through json, enter url, enter json body, and enter content type = Application / json.
-
The back-end processing logic is as follows:
package main import ( "github.com/gin-gonic/gin" "net/http" ) // Login Binding from JSON type Login struct { UserName string `form:"username" json:"username" binding:"required"` Password string `form:"password" json:"password" binding:"required"` } func main() { //Set gin mode gin.SetMode(gin.ReleaseMode) //Create a new routing engine r := gin.New() // Examples of binding JSON ({"username": "Zhang San", "password": "123456"}) r.POST("/loginJSON", func(ctx *gin.Context) { // Create a structure type instance login := Login{} if err := ctx.ShouldBind(&login); err == nil { ctx.JSON(http.StatusOK, gin.H{ "message": "login with json query", "username": login.UserName, "password": login.Password, }) } else { ctx.JSON(http.StatusBadRequest, gin.H{ "err_no": err.Error(), }) } }) // Binding form example (user = Zhang San & password = 123456) r.POST("/loginForm", func(ctx *gin.Context) { login := Login{} // ShouldBind() will choose the binder according to the requested content type if err := ctx.ShouldBind(&login); err == nil { ctx.JSON(http.StatusOK, gin.H{ "message": "login with form query", "username": login.UserName, "password": login.Password, }) } else { ctx.JSON(http.StatusBadRequest, gin.H{ "error": err.Error(), }) } }) // Binding QueryString example (/ loginQuery?user = Zhang San & password = 123456) r.GET("/loginQuery", func(ctx *gin.Context) { login := Login{} // ShouldBind() will choose the binder according to the requested content type if err := ctx.ShouldBind(&login); err == nil { ctx.JSON(http.StatusOK, gin.H{ "message": "login with querystring query", "username": login.UserName, "password": login.Password, }) } else { ctx.JSON(http.StatusBadRequest, gin.H{ "error": err.Error(), }) } }) // Start the HTTP service. By default, the service is started at port 8080. It can also be set to other ports, such as 8000 r.Run(":8080") }
ShouldBind will parse the data in the request in the following order to complete the binding:
- If it is a GET request, only the Form binding engine (query) is used.
- If it is a POST request, first check whether the content type is JSON or XML, and then use Form (Form data).
So far, we have learned how the gin framework obtains the request parameters.