The gin of golang network framework

golang native http library can easily implement an http server, but for complex web services, such as routing analysis, request parameter analysis, ob...
hello world
Request parameter resolution
Return packet
File upload and return
cros cross domain
cookies
link

golang native http library can easily implement an http server, but for complex web services, such as routing analysis, request parameter analysis, object return, etc., native api is not enough, and gin is a web network framework with complete functions and high performance, especially suitable for the development of web api

hello world

package main import "github.com/gin-gonic/gin" func main() { r := gin.New() r.GET("/ping", func(c *gin.Context) { c.String(200, "hello world") }) r.Run() // listen and serve on 0.0.0.0:8080 }

All business logic of gin as shown in this hello world program is implemented in func(c *gin.Context) function, and requests and returns are passed through this gin.Context

Request parameter resolution

gin provides rich ways to obtain request parameters

(c *Context) Query(key string) string // GET parameters (c *Context) QueryArray(key string) []string // GET get parameter array (c *Context) DefaultQuery(key, defaultValue string) // GET the GET parameter and provide the default value (c *Context) Param(key string) string // Get Param parameter, similar to "/ user/:id" (c *Context) GetRawData() ([]byte, error) // Get body data

But I don't recommend using any of these functions. I suggest using the structure to describe the request, and then using the bind api to get the request parameters directly

type HelloWorldReq struct { Token string `json:"token"` ID int `json:"id" uri:"id"` Email string `json:"email" form:"email"` Password string `json:"password" form:"password"` } req := &HelloWorldReq{ Token: c.GetHeader("Authorization"), // The header field cannot be bound. You can get it through GetHeader } // Fill the uri field in the structure with the Param parameter in the request if err := c.BindUri(req); err != nil { return nil, nil, http.StatusBadRequest, fmt.Errorf("bind uri failed. err: [%v]", err) } // Fill form field with Query parameter in GET request // Non GET request, deserialize json or xml in body and fill in form field if err := c.Bind(req); err != nil { return nil, nil, http.StatusBadRequest, fmt.Errorf("bind failed. err: [%v]", err) }

The client IP of http is generally in the x-forward-for and X-Real-Ip of the request header. In provides (c *Context) ClientIP() string to obtain the IP

Return packet

(c *Context) String(code int, format string, values ...interface{}) // Returns a string (c *Context) JSON(code int, obj interface{}) // Return a json (c *Context) Status(code int) // Return a status code

File upload and return

Get file from request

fh, err := ctx.FormFile("file") if err != nil { return err } src, err := fh.Open() if err != nil { return err } defer src.Close()

Return file

(c *Context) File(filepath string)

cros cross domain

There is a field "access control allow Origin" in the header returned by the server. If the field is different from the requested domain, the browser will be rejected by the browser. In fact, I understand that the client does not have permission to access the field, the server should not return the result, and the browser thinks the result is not available, so it prompts cross domain error, and the header field can only write an address, Or write *, which is open to all websites. To develop multiple websites, we can dynamically set the "access control allow Origin" field according to the "Origin" field of the request, and set it to the "Origin" field in the request if the permission is satisfied. A plug-in of gin, github.com/gin-contrib/cors, is specially used for this purpose. You can set it in AllowOrigins Multiple websites, you can also set wildcards (you need to set AllowWildcard to true)

import "github.com/gin-contrib/cors" r := gin.New() r.Use(cors.New(cors.Config{ AllowOrigins: []string{"a.example.com", "b.example.com"}, AllowMethods: []string{"PUT", "POST", "GET", "OPTIONS"}, AllowHeaders: []string{"Origin", "Content-Type", "Content-Length", "Accept-Encoding", "X-CSRF-Token", "Authorization", "Accept", "Cache-Control", "X-Requested-With"}, AllowCredentials: true, }))

cookies

// maxAge is the expiration time // Domain is the address of the website. To share cookie s across domains, you can set it as a domain name, // For example, a.example.com and b.example.com can set the domain to example.com // Set security to https to true and http to false // httpOnly is set to false, otherwise the cookie s cannot be accessed by libraries such as axios (c *Context) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool)

In addition, axios needs to set with credentials: true cookie to return normally

link

Reprint please indicate the source
Link to this article: https://tech.hatlonely.com/article/55

27 November 2019, 08:23 | Views: 6220

Add new comment

For adding a comment, please log in
or create account

0 comments