Gin framework notes

Environment construction and installation

  1. Set proxy image

    Due to the slow speed of accessing GitHub and possible permission problems, we need to set up a proxy

    go env -w GOPOXY=https://goproxy.io,direct
    
  2. Download the gin framework

    go get -u github.com/gin-gonic/gin
    
  3. First code

    func main() {
        r := gin.Default()//Engine initialization
        r.GET("/hello", func(c *gin.Context) {//context is a text tool
            fmt.Println(c.FullPath())	//Print port number
            c.Writer.Write([]byte("Hello gin\n"))
            //Write a slice data to get request
        })
        r.Run() // Listen and start the service on 0.0.0.0:8080
    }
    

    To specify a port

    r.Run(":8090")	//Running on port: 8090
    

Request processing

Engine creation

The following two statements are used to create the engine.

engine1 = gin.Default()
engine2 = gin.New()

The difference between the two statements is gin Default () also uses gin New() creates an engine instance, but it will call Logger and Recovery middleware by default, which is more convenient for operation.

Logger is a middleware responsible for printing and outputting logs, which is convenient for developers to debug programs; REcovery will resume program execution and return an internal error of server 500. Usually, we use gin. Com by default Default() creates an Engine instance.

Processing statement

Handle general request

engine.Handle(`method`"GET",`path`"/hello",func(c *gin.Context){
    
})

GET request

Basic framework
engine.GET("`route`path",func(context *gin.Context`Context structure`){
    "Related operations"
})
Related operations
//http://localhost:8080/hello?name=Goland

//Call path
fmt.Println(context.FullPath())

//Two methods of parsing path value
name := context.DefaultQuery(`key value:`"name",`Default value:`"hello")
name := context.Query(`key value:`"name")

POST request

Basic framework
engine.POST("`route`path",func(context *gin.Context){
    
})
Related operations
//http://localhost:8080/login
//Content in form

fmt.Println(context.FullPath())

//Get corresponding value
username := context.PostForm("username")

//Obtain the corresponding value and return whether it is obtained successfully
password,exist:= context.GETPostForm("password")
if exist{
   context.Writer.Write([]byte("Password obtained successfully"))
}

DELETE request

Basic framework

Since the id is variable, use: to obtain the value of id.

engine.DELETE("/user/:id",func(context *gin.Context){
    
})
Related operations
//Gets the variable whose ID is the location of the instance
userID := context.Param(`key value`"id")

Comprehensive example

//http://localhost:8080/hello?name=Goland
engine := gin.Default()

//GET request
engine.GET("path",func(context *gin.Context){
    fmt.Println(context.FullPath())
    
    //First, if the value of name cannot be queried, a default value will be given to name
    name := context.DefaultQuery(`key:`"name",`default:`"hello")
    
    //Second, direct query has no default value
    name := context.Query(`key:`"name")
})

//POST request
engine.POST("path",fun(context *gin.Context){
    fmt.Println(context.FullPath())
    
   	//The first method only obtains the corresponding value
    username := context.PostForm("corresponding key value(for example username)") 
    
   	//The second parameter will return the second parameter, indicating whether the corresponding value has been obtained
    username,exist := context.GetPostForm(`key:`"username")
    
    //Judge whether it is obtained, and then process it
    if exist{
        "Corresponding processing"
        fmt.Println(username)
    }
})

//DELETE request
engine.DELETE("/user/:id",func(context *gin.Context){
    //Get id location variable
    uesID := context.Param("id")
   
})

Request parameter binding and multi data processing format

Leading

Through the basic study of request processing, we can learn how to obtain form data. However, in our example, only username and password need to be obtained, but in the actual project, we need to obtain multiple data. In this way, the development efficiency of obtaining one data at a time is relatively slow and the encapsulation is poor.

The Gin framework provides the function of form entity binding, which can bind form data with our own defined structure.

Form entity binding

Gin framework provides the function of data structure and form submission data binding to improve the efficiency of expression data acquisition. As follows:

Take a student's learning acquisition as an example. When the form is submitted, it contains two data: Name and Classes

type Student struct{
    Name string `form:"name" binding:"required"`
    Classes string `form:"classes" binding:"required"`
}

Create a Student structure to accept Student data. Set the attribute name of the form (binding) corresponding to each data field in the structure by tag tag. Binding sets whether the attribute is required. It is required by default.

One important point to note here is that the variable definition in the structure must be uppercase, otherwise the corresponding bound value cannot be successfully obtained.

ShouldBindQuery

ShouldBindQuery can be used to bind data requests in GET mode, as follows:

func main(){
    
    engine := gin.Default()
    
    //htpp://localhos:8080/hello?name=davie&classes= software engineering
    engine.GET("/hello",func(context *gin.Context){
        fmt.Println(context.FullPath())
        //Define structure variables
        var stu Student
        //Define the error return information. If stu is bound successfully, there is no return value
        err := context.ShouldBindQuery(&stu)
        if err != nil{
            //Binding failed, output error log
            log.Fatal(err.Error())
            return
        }
        
        fmt.Println(stu.Name)
        fmt.Println(stu.Classes)
        context.Writer.Write([]byte("hello," + stu.Name))
    })
    
}

type Student struct{
    Name string `form:"name"`
    Classes string `form:"classes"`
}

Here we touch the package statement of log, log Fatal (output content) is used to output logs to facilitate developers to query errors.

ShouldBind

ShouldBind can be used to bind data submitted in Post mode, as follows:

func main() {

    engine := gin.Default()

    engine.POST("/register", func(context *gin.Context) {
        fmt.Println(context.FullPath())
        //Define structure variables
        var reg Register
        //Bind and judge whether the binding is successful
        if err := context.ShouldBind(&reg); err != nil {
            log.Fatal(err.Error())
            return
        }

        fmt.Println(reg.UserName)
        fmt.Println(reg.Phone)
        context.Writer.Write([]byte(reg.UserName + " Register "))

    })

    engine.Run()
}

type Register struct {
    UserName string form:"name"
    Phone    string form:"phone"
    Password string form:"pwd"
}

ShouldBindJson

When the client submits data in Json format, ShouldBindJson can be used to bind the data

func main() {

    engine := gin.Default()

    engine.POST("/addstudent", func(context *gin.Context) {
        fmt.Println(context.FullPath())
        //1
        var person Person
        //2
        if err := context.BindJSON(&person); err != nil {
            log.Fatal(err.Error())
            return
        }

        fmt.Println("full name:" + person.Name)
        fmt.Println("Age:", person.Age)
        context.Writer.Write([]byte(" Add record:" + person.Name))
    })

    engine.Run()
}

type Person struct {
    Name string form:"name"
    Sex  string form:"sex"
    Age  int    form:"age"
}

Keywords: Go

Added by chancho on Mon, 24 Jan 2022 03:24:49 +0200