gin golang network framework

http golang native libraries already can easily implement a http server, but for complex web services, the routing resolution, request parameter analysis, object returns, etc., native api it is somewhat good enough, and gin is a fully functional, high performance web network framework, in particular 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
}

As this hello worldprocedure gin shown in all the business logic func(c *gin.Context)implemented function, and return the request is transmitted through this gin.Context

Request parameter parsing

gin provides a wealth of request parameters acquisition mode

(c *Context) Query(key string) string               // 获取 GET 参数
(c *Context) QueryArray(key string) []string        // 获取 GET 参数数组
(c *Context) DefaultQuery(key, defaultValue string) // 获取 GET 参数,并提供默认值
(c *Context) Param(key string) string               // 获取 Param 参数,类似于 "/user/:id"
(c *Context) GetRawData() ([]byte, error)           // 获取 body 数据

But I do not recommend the use of these functions, it is recommended to describe the structure for the request, and then use the bind api directly to the acquisition request parameter

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"),    // 头部字段无法 bind,可以通过 GetHeader 获取
}

// 用请求中的 Param 参数填充结构体中的 uri 字段
if err := c.BindUri(req); err != nil {
    return nil, nil, http.StatusBadRequest, fmt.Errorf("bind uri failed. err: [%v]", err)
}

// GET 请求中用 Query 参数填充 form 字段
// 非 GET 请求,将 body 中的 json 或者 xml 反序列化后填充 form 字段
if err := c.Bind(req); err != nil {
    return nil, nil, http.StatusBadRequest, fmt.Errorf("bind failed. err: [%v]", err)
}

Usually ip http client request header X-Forwarded-Forand X-Real-Ipthe, gin provided (c *Context) ClientIP() stringto obtain ip

Return package body

(c *Context) String(code int, format string, values ...interface{}) // 返回一个字符串
(c *Context) JSON(code int, obj interface{})                        // 返回一个 json
(c *Context) Status(code int)                                       // 返回一个状态码

File upload and return

Get the file from the request

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

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

Returns the file

(c *Context) File(filepath string)

cros cross-domain

Head returned from the server There is a field "Access-Control-Allow-Origin ", if the field and request a different domain, the browser will be denied the browser, in fact, I understand that this place should be the client does not have permission to access, the server should not return a result, the browser thinks the results are not available, so prompt cross-domain error, and this header field can only write an address, or written *, are open to all sites, in order to develop multiple sites, we can "Origin" field of the request, dynamically set the "Access-Control-Allow-Origin " field, permission was set to meet the request of the "Origin" field, gin has a plug-in github.com/gin-contrib/corsis designed to make this thing , you can set up multiple websites AllowOrigins, you can also set up a wildcard (to be set AllowWildcardfor the 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 为过期时间
// domain 是网站的地址,如需跨域共享 cookie,可以设置成域名,
//      比如 a.example.com 和 b.example.com,可以将 domain 设置成 example.com
// secure 为 https 设为 true,http 设为 false
// httpOnly 设置为 false,否则 axios 之类的库访问不到 cookie
(c *Context) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool)

In addition, axios need to set the withCredentials: truecookie to return to normal

link

Please indicate the source
article link: https://tech.hatlonely.com/article/55

Guess you like

Origin www.cnblogs.com/hatlonely/p/11945327.html