The source code

Github.com/zsl10/gin-e…

Data binding

  • Gin provides a very convenient data binding capability that automatically binds the parameters sent by the user to the structure we define.
  • A model binding can bind the request body to a type, currently supported for JSON, XML, and standard form data (foo= bar&Boo =baz).
  • When binding, you need to set the label of the binding type for the field. For example, when binding JSON data, set JSON to “fieldName”. When using the binding method, Gin automatically determines the Type to be resolved based on the Content-Type in the request header. If you specify the type of binding, you can use the BindWith method instead of automatically inferring.
  • You can specify that a field is required. If a field is decorated with binding:”required” and the value is empty, the request fails and an error is returned.

The code examples

package main

import (
	"github.com/gin-gonic/gin"
	"net/http"// Define the structure for receiving data // binding:"required": Verification rule, cannot be emptytype Login struct {
	User     string `form:"user" json:"user" binding:"required"`
	Password string `form:"password" json:"password" binding:"required"`
}

func main() {router := gin.Default() // 1) bind url query router.get ()"/test/url/query", func(c *gin.Context) {// Declare the received variable var urlQuery Login // Automatically parse the data in the request query into the structureiferr := c.ShouldBindQuery(&urlQuery); err ! = nil { c.String(http.StatusBadRequest, err.Error()) } c.String(http.StatusOK,"Success"}) // 2) bind the form parameter router.post ("/form", func(c *gin.Context) {
		var form Login
		iferr := c.Bind(&form); err ! = nil { c.String(http.StatusBadRequest, err.Error()) } c.String(http.StatusOK,"Success"}) // 3) Bind json data router.post ("/json", func(c *gin.Context) {
		var json Login
		iferr := c.ShouldBindJSON(&json); err ! = nil { c.String(http.StatusBadRequest, err.Error()) } c.String(http.StatusOK,"Success")
	})




	router.Run(": 8080")}Copy the code