gin中如何自定义中间件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package main
 
import (
    "fmt"
    "github.com/gin-gonic/gin"
)
 
func main() {
    // 新建一个没有任何默认中间件的路由
    router := gin.New()
 
    // Logger 中间件将日志写入 gin.DefaultWriter,即使你讲GIN.MODE设置为release
    // gin.DefaultWriter io.Writer = os.Stdout
    router.Use(gin.Logger())
 
    // Recovery 中间件会 recover 任何 panic,如果有panic的话,会写入500
    router.Use(gin.Recovery())
 
    // 使用自定义的中间件
    router.Use(RequestInfos())
    router.Use(RequestInfos2())
    router.Use(func(context *gin.Context) {
        url := context.Request.URL
        fmt.Println(url)
    })
 
    router.GET("/json", func(context *gin.Context) {
        context.JSON(200, "OK")
    })
 
    router.Run()
}
 
func RequestInfos() gin.HandlerFunc {
    return func(context *gin.Context) {
        path := context.FullPath()
        method := context.Request.Method
        fmt.Printf("path: %s, method: %s\n", path, method)
        context.Next()
        fmt.Println(context.Writer.Status())
    }
}
 
func RequestInfos2() gin.HandlerFunc {
    return func(context *gin.Context) {
        fmt.Println("requestInfo2执行了")
    }
}
 
/* 显示RequestInfos中的第一个print打印,然后RequestInfos2的print打印
   然后再回到RequestInfos中的context.Next()下面继续执行,最后输出日志信息
path: /json, method: GET
requestInfo2执行了
/json
200
[GIN] 2021/10/22 - 14:32:19 | 200 |            0s |             ::1 | GET      "/json"
*/

  

posted @   专职  阅读(226)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示