首页  >  文章  >  后端开发  >  Go/Gin 调试输出的含义是什么 - (x handlers)

Go/Gin 调试输出的含义是什么 - (x handlers)

WBOY
WBOY转载
2024-02-09 08:15:19457浏览

Go/Gin 调试输出的含义是什么 - (x handlers)

php小编柚子为您解答Go/Gin调试输出中的"(x handlers)"的含义。在Go语言的Gin框架中,"(x handlers)"代表请求经过的中间件数量。中间件是Gin框架中用于处理请求的一种机制,可以在请求到达路由处理函数之前或之后执行一些操作。每个中间件都会将请求传递给下一个中间件,直到最终到达处理函数。"(x handlers)"中的"x"表示中间件的数量,它可以帮助开发者了解请求处理过程中经过了多少个中间件的处理。通过观察中间件数量,开发者可以更好地理解请求的处理流程,方便调试和优化代码。希望这个解答对您有所帮助!

问题内容

在下面的 go/gin 调试输出中,(5 handlers) 的含义是什么。正如您所看到的,我显然有超过 5 个处理程序。

[GIN-debug] GET    /                         --> .../handlers.APIDetail (5 handlers)
[GIN-debug] POST   /signup                   --> .../handlers.SignUp (5 handlers)
[GIN-debug] POST   /signin                   --> .../handlers.SignIn (5 handlers)
[GIN-debug] POST   /refresh-token            --> .../handlers.RefreshToken (5 handlers)
[GIN-debug] POST   /verify-email             --> .../handlers.VerifyEmailVerificationToken (5 handlers)
[GIN-debug] POST   /resend-verification-email --> .../handlers.ResendEmailVerificationEmail (5 handlers)
[GIN-debug] POST   /reset-password           --> .../handlers.ResetPassword (5 handlers)
[GIN-debug] POST   /change-password          --> .../handlers.ChangePassword (5 handlers)
[GIN-debug] PATCH  /users/me                 --> .../handlers.UpdateProfile (5 handlers)
[GIN-debug] POST   /signout                  --> .../handlers.SignOut (5 handlers)
[GIN-debug] GET    /orgs/:id                 --> .../handlers.GetOrganizations (5 handlers)
[GIN-debug] GET    /orgs                     --> .../handlers.GetOrganizations (5 handlers)

解决方法

它应该是每个路由的处理程序链中的处理程序数量,即当请求路由到某个端点时将执行的处理程序(包括中间件)的最大数量。

相关代码来自gin 来源@latest

func debugprintroute(httpmethod, absolutepath string, handlers handlerschain) {
    if isdebugging() {
        nuhandlers := len(handlers)
        handlername := nameoffunction(handlers.last())
        if debugprintroutefunc == nil {
            debugprint("%-6s %-25s --> %s (%d handlers)\n", httpmethod, absolutepath, handlername, nuhandlers)
        } else {
            debugprintroutefunc(httpmethod, absolutepath, handlername, nuhandlers)
        }
    }
}

如果您正在设置一些全局中间件,例如使用 router.use,在声明路由之前,并且没有路由具有每个路由的中间件,这解释了为什么数字总是相同的。

例如,请考虑以下内容:

r.use(func(*gin.context) { fmt.println("first") })
    r.get("/foo", func(c *gin.context) {
        c.status(http.statusok)
    })

    r.use(func(*gin.context) { fmt.println("second") })
    r.get("/bar", func(c *gin.context) {
        c.status(http.statusok)
    })

打印:

[GIN-debug] GET    /foo    --> main.main.func2 (2 handlers)
[GIN-debug] GET    /bar    --> main.main.func4 (3 handlers)

因为 /foo 的链有 first 中间件和处理程序本身 (2),而 /bar 的链有 firstsecond 中间件,加上处理程序本身 (3)。

以上是Go/Gin 调试输出的含义是什么 - (x handlers)的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:stackoverflow.com。如有侵权,请联系admin@php.cn删除