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
func Include(opts ...Option) {
options = append(options, opts...)
}
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:
func RandomMiddleWare() gin.HandlerFunc {
return func(c *gin.Context) {
c.Set("randomValue", RandStringRunes(20))
c.Next()
fmt.Printf("返回请求后再执行\n")
}
}
该请求的随机值是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