首頁  >  文章  >  後端開發  >  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刪除