03-Gin middleware

1: Global middleware

1.1: Simple middleware example

  • Implemented function: Append a random value before each request.
  • Implementation of random value middleware
package middleware

import (
	"github.com/gin-gonic/gin"
	"math/rand"
	"time"
)

func init() {
	rand.Seed(time.Now().UnixNano())
}

var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")

func RandStringRunes(n int) string {
	b := make([]rune, n)
	for i := range b {
		b[i] = letterRunes[rand.Intn(len(letterRunes))]
	}
	return string(b)
}

// RandomMiddleWare MiddleWare 随机值中间件,每个请求进来, 我们都产生一个随机值, 存放在上下文中。
func RandomMiddleWare() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 随机值中间件会在请求上下文中, 设置一个随机值
		c.Set("randomValue", RandStringRunes(20))
	}
}

  • Register the middleware into the engine
package routers

import (
	"github.com/gin-gonic/gin"
	"learn_gin/middleware"
)

type Option func(*gin.Engine)

var options []Option

// Include 将APP中的路由放入options切片中
func Include(opts ...Option) {
    
    
	options = append(options, opts...)
}

// Init 初始化引擎, 并将路由注册到引擎中
func Init() *gin.Engine {
    
    
	engine := gin.Default()
	// 注册中间件
	engine.Use(middleware.RandomMiddleWare())
	for _, opt := range options {
    
    
		opt(engine)
	}
	return engine
}

1.2: Run the second half of the middleware after controlling the request

  • Next() function control
  • Code example:
// RandomMiddleWare MiddleWare 随机值中间件,每个请求进来, 我们都产生一个随机值, 存放在上下文中。
func RandomMiddleWare() gin.HandlerFunc {
    
    
	return func(c *gin.Context) {
    
    
		// 随机值中间件会在请求上下文中, 设置一个随机值
		c.Set("randomValue", RandStringRunes(20))
		// 阻断
		c.Next()
		fmt.Printf("返回请求后再执行\n")
	}
}
  • running result:
该请求的随机值是PVaxecLBhcWXDbIkaxHU
返回请求后再执行
[GIN] 2022/09/08 - 18:05:56 | 200 |     218.628µs |       127.0.0.1 | GET      "/animal/login?name=root&password=123456"

Two: Partial middleware

  • 1: Partial middleware is not registered in the engine
  • 2: You can add local middleware to the route, and only certain routes will use this middleware.
func Routers(e *gin.Engine) {
    
    
	e.GET("/animal/login", middleware.RandomMiddleWare(), testArgs)
}

Three: Commonly used middleware

  • Refer to the official website recommendation
    • https://github.com/gin-gonic/contrib/blob/master/README.md

Guess you like

Origin blog.csdn.net/qq_41341757/article/details/126769698