关于自定义中间件后执行的问题
来源:1-11 自定义gin中间件
舞步轻盈
2021-08-18 21:13:59
问题描述:
示例中c.Next()后的代码为什么会执行两次呢?
相关代码:
package main
import (
"github.com/gin-gonic/gin"
"log"
"time"
)
func Logger() gin.HandlerFunc {
return func(c *gin.Context) {
t := time.Now()
// Set example variable
c.Set("example", "12345")
// before request
c.Next()
// after request
latency := time.Since(t)
log.Print(latency)
// access the status we are sending
status := c.Writer.Status()
log.Println(status)
}
}
func main() {
r := gin.New()
r.Use(Logger())
r.GET("/test", func(c *gin.Context) {
example := c.MustGet("example").(string)
// it would print: "12345"
log.Println(example)
})
// Listen and serve on 0.0.0.0:8080
r.Run(":8081")
}
相关截图:

请老师解答。
2回答
如果要解决这个问题 需要继续看一下gin的源码才行
舞步轻盈
提问者
2022-05-13
main gingint timelatency timetloglatencystatus Writerlogstatusr ginrrginexample logexampler
以上是源码,其实不会像问题描述的真正的执行两次。是我操作有问题。
复现方法:
执行一次
http://localhost:8081
再执行一次 http://localhost:8081/test
相似问题
回答 1
回答 1