在這種情況下,您使用的中間件從請求正文中解析JWT 並希望將其傳遞給您的處理程序以避免冗餘解析。由於您的中介軟體傳回 http.Handler 並且您的處理程序也傳回一個 http.Handler,因此有必要找到在它們之間傳遞 JWT 的方法。
一種建議的方法是利用 Gorilla Mux 中的 context 套件。 context 套件可讓您以類型安全的方式儲存與請求關聯的值。
import ( "github.com/gorilla/context" ) // Middleware serves as a wrapper around the next handler. func Middleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Middleware operations // Parse body/get token. token, err := getTokenFromRequest(r) if err != nil { http.Error(w, "Error getting token", http.StatusInternalServerError) return } context.Set(r, "token", token) next.ServeHTTP(w, r) }) } // Handler retrieves the JWT from the request context. func Handler() http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { token := context.Get(r, "token") // Use the token in your handler logic. }) }
透過使用 context 包,您可以將解析後的 JWT 儲存在中間件的請求上下文中並輕鬆存取它在你的處理程序中,而不需要重新解析。
更新:
值得注意的是,Gorilla 上下文套件現在處於維護模式。對於新項目,建議使用 Go 1.7 中引入的 context.Context() 功能,它提供了更健壯、更有效率的管理請求上下文資料的方法。
以上是如何在 Go 中將資料從中間件傳遞到處理程序?的詳細內容。更多資訊請關注PHP中文網其他相關文章!