What is the Gin

High-performance HTTP framework written in the Go language.

The characteristics of Gin

  1. Fast – Small memory footprint, no reflection
  2. Support middleware – can recoverHTTP requests in panic, ensure that the server is always available
  3. JSON validation – Checks that the required value exists
  4. Routing groups – Better organization of apis, and routing groups can be infinitely nested
  5. Error management – Makes it easy to collect errors in HTTP requests and write them to log files
  6. Built-in rendering – easy to render to JSON, XML and HTML
  7. Extensibility – it is easy to create a new middleware

Installation and use of Gin

  1. Download and install Gin

    Type the following command in the terminal

     go get -u github.com/gin-gonic/gin
    Copy the code
  2. Introduce Gin into the project

    Import (• "github.com/gin-gonic/gin" "net/ HTTP ")Copy the code
  3. If you want to use the status codes defined in the Go language, introduce the “NET/HTTP” package, otherwise don’t

    For example,

    Http.statusok // represents the constant 200Copy the code

    Here are just a few of the constant definitions under the “NET/HTTP” package

    StatusOK = 200 // RFC 7231, 6.3.1 StatusCreated = 201 // RFC 7231, 6.3.2 StatusAccepted = 202 // RFC 7231, 6.3.3 StatusNonAuthoritativeInfo = 203 / / RFC 7231, 6.3.4 StatusNoContent = 204 / / RFC 7231, 6.3.5 StatusResetContent = 205 // RFC 7231, 6.3.6 StatusPartialContent = 206 // RFC 7233, 4.1 StatusMultiStatus = 207 // RFC 4918, 11.1 StatusAlreadyReported = 208 // RFC 5842, 7.1 StatusIMUsed = 226 // RFC 3229, 10.4.1Copy the code

Simple use of Gin

R := Gin.Default() // Register the URL of /gin_use r.get ("/gin_use", func(c * Gin.Context) {c.son (http.statusok, Gin.H{"code": 200, "MSG ": "/gin_use request is successful ",})}) /* Make gin make HTTP request 127.0.0.1 / localhost */ r.run ()Copy the code

Request mode supported by Gin

GET, POST, PUT, DELETE, HEAD, PATCH, OPTIONS

GET The data in the request

Query & DefaultQuery

R.geet ("/user_login", func(c *gin.Context) {// query the specified request parameter, if not, set a default value username := c.defaultQuery ("username", // Query the specified request parameter password := c.uiery ("password") c.son (200, gin.H{"username":username, "password":password, })})Copy the code

ShouldBind

Type LoginData struct {Username string 'form:" Username "binding:"required"' Password string `form:"password" binding:"required"` } r.GET("/login", Func (context *gin.Context) {var loginData loginData // Explicitly declare the binding mode //err := Context.shouldbindwith (&loginData, binding.form) // receives data via a struct type variable, = context.shouldbind (&loginData) if err! = nil {fmt.println (err)} else {// return a json format context. Json (200, err)} else {// return a json format context. Gin.H{"username": logindata.username, "password": logindata.password, "MSG ":" request succeeded ",})}})Copy the code

BindUri

// Define a structure, Type Person struct {Name string 'Uri :" Name "binding:"required"' Age int 'Uri :" Age" binding:"required"'} type Person struct {Name string 'Uri :" Name "binding:"required"' Age int 'Uri :" Age" binding:"required"'} r.GET("/bindUri/:name/:age", func(c *gin.Context) { var person Person err := c.BindUri(&person) if err ! = nil { c.JSON(400, err.Error()) } else { c.JSON(200, &person) } })Copy the code

Data in the POST request

PostForm & DefaultPostForm

R.post ("form_post", func(c * gin.context) {message := c. post form ("message") // If the form has no key, Then set a default value Nick := c.defaultPostForm (" Nick ", "shaosiming") c.son (200, gin.H{"message":message, "Nick ": Nick, "MSG ":" sent successfully ",})})Copy the code

ShouldBindJSON

R.pust ("/bindJSON", func(c *gin.Context) {var user LoginData // request body is JSON format data, Err := c. sondbindjson (&user) if err == nil {c.son (200, &user)} else {c.son (400, err.error ())}})Copy the code

The data format of the response

JSON

R. gutierrez ET ("/somejson ", the func (c * gin in the Context) {SAN Antonio SON (200, gin. H {" code ": 0," MSG ":" json request is successful, "})})Copy the code

struct

// struct r.GET("/struct", Var user struct{Name string Age int} user.Name = "shaosiming" user.Age = 18 // You can also treat variables of struct type as return types c.son (200, &user)})Copy the code

XML

R.get ("/someXML", func(c *gin.Context) {// convert a map to XML and return c.XML(200, gin.H{"code":0, "MSG ":" XML request succeeded ",})})Copy the code

Upload a single file

R.file ("/single_upload", func(c *gin.Context) {err := c. file ("file") if err! = nil {fmt.println (err)} else {fmt.println (file.filename) // Save to the file directory DST := "./" + file.filename C.son (200, gin.H{"code":0, "MSG ":file.Filename +" upload successfully ",})}})Copy the code

You can use curl to test

curl -X POST http://localhost:8080/single_upload -F “file=@/Users/Shaosiming/Desktop/test.png” -H “Content-Type: multipart/form-data”

Multiple file uploads

r.POST("/multi_upload", func(c *gin.Context) { form, File := form.file ["upload[]"] // save the File to the specified directory for _, file := range files { log.Println(file.Filename) dst := "./" + file.Filename; J (200, gin.H{"code":0, "MSG ":" multiple files successfully ",})} c (200, gin.H{"code":0," MSG ":" multiple files successfully ",})Copy the code

You can use curl to test

curl -X POST http://localhost:8080/multi_upload -F “upload[]=@/Users/Shaosiming/Desktop/test1.png” -F “upload[]=@/Users/Shaosiming/Desktop/test2.png” -H “Content-Type: multipart/form-data”

Use of routing groups

Note: Routing groups can be nested indefinitely

GET("/login", func(c *gin.Context) {c.son (200, gin. "MSG", "the login request is successful,"})}) v1. GET ("/update ", the func (c * gin in the Context) {SAN Antonio SON (200, gin. H {" version ": 1.0," MSG ":" the update request is successful," R. gutierrez roup})})} v2: = ("/v2 ") {v2. GET ("/login ", func (c * gin in the Context) {SAN Antonio SON (200, gin. H {" version ": 2.0. "MSG", "the login request is successful,"})}) v2. GET ("/update ", the func (c * gin in the Context) {SAN Antonio SON (200, gin. H {" version ": 2.0," MSG ":" the update request is successful," })})}Copy the code

redirect

R.geet ("goto_baidu", func(c * gin.context) {c.redirect (301, "https://www.baidu.com/")}) r.get ("/redirect2", func(c *gin.Context) {c.redirect (301, "/redirect3")}) r.gt ("/redirect3", func(c *gin.Context) {c SON(200, "direct3")}) func(c *gin.Context) { c.Request.URL.Path = "/redirect5" r.HandleContext(c) }) r.GET("/redirect5", func(c *gin.Context) { c.JSON(200, "direct5") })Copy the code