如何將Golang 請求中的上下文傳遞給中間件
理解上下文
Go 的上下文,在1.7 版本中引入,是將元資料與請求相關聯的機制。它允許您在程式碼的不同部分之間傳遞訊息,包括中間件和處理程序。
將上下文傳遞給中間件
您的問題提出瞭如何傳遞中間件和處理程序的上下文。為了與您提供的範例程式碼保持一致,checkAuth 函數將代表中間件,而 Handler 代表處理程序。
要將上下文傳遞給中間件,您通常會在請求物件上使用 WithContext 方法。例如:
func checkAuth(authToken string) http.HandlerFunc { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() // Retrieve the current context from the request if r.Header.Get("Auth") != authToken { util.SendError(w, "...", http.StatusForbidden, false) return } h := r.Context().Value(key) // Retrieve the handler from context h.ServeHTTP(w, r) // Pass the request to the handler }) }
將上下文傳遞給處理程序
要將上下文傳遞給處理程序,您將再次在請求對像上使用 WithContext 方法。在處理程序的ServeHTTP 方法中,您可以使用Value 方法檢索上下文:
func (h *HandlerW) ServeHTTP(w http.ResponseWriter, r *http.Request) { ctx := r.Context() // Retrieve the context from the request decoder := json.NewDecoder(r.Body) // Decode request / context and get params var p params err := decoder.Decode(&p) if err != nil { ... return } // Perform GET request and pass context ... }
範例用法
您的main 函數可能如下所示:
func main() { router := mux.NewRouter() // Initialize middleware handlers h := Handler{ ... } // Pass context to authCheck authToken, ok := getAuthToken() if !ok { panic("...") } authCheck := checkAuth(authToken) // Chain middleware handlers and pass context router.Handle("/hello", util.UseMiddleware(authCheck, h, ...)) }
請記住,上下文只能用來傳遞瞬態訊息。對於更持久的數據,請使用資料庫或其他儲存機制。
以上是如何將 Golang 請求中的上下文傳遞給中間件和處理程序?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

在Go編程中,有效管理錯誤的方法包括:1)使用錯誤值而非異常,2)採用錯誤包裝技術,3)定義自定義錯誤類型,4)復用錯誤值以提高性能,5)謹慎使用panic和recover,6)確保錯誤消息清晰且一致,7)記錄錯誤處理策略,8)將錯誤視為一等公民,9)使用錯誤通道處理異步錯誤。這些做法和模式有助於編寫更健壯、可維護和高效的代碼。

在Go中實現並發可以通過使用goroutines和channels來實現。 1)使用goroutines來並行執行任務,如示例中同時享受音樂和觀察朋友。 2)通過channels在goroutines之間安全傳遞數據,如生產者和消費者模式。 3)避免過度使用goroutines和死鎖,合理設計系統以優化並發程序。

Gooffersmultipleapproachesforbuildingconcurrentdatastructures,includingmutexes,channels,andatomicoperations.1)Mutexesprovidesimplethreadsafetybutcancauseperformancebottlenecks.2)Channelsofferscalabilitybutmayblockiffullorempty.3)Atomicoperationsareef

go'serrorhandlingisexplicit,治療eRROSASRETRATERTHANEXCEPTIONS,與pythonandjava.1)go'sapphifeensuresererrawaresserrorawarenessbutcanleadtoverbosecode.2)pythonandjavauseexeexceptionseforforforforforcleanerCodebutmaymobisserrors.3)

whentestinggocodewithinitfunctions,useexplicitseTupfunctionsorseParateTestFileSteSteTepteTementDippedDependendendencyOnInItfunctionsIdeFunctionSideFunctionsEffect.1)useexplicitsetupfunctionStocontrolglobalvaribalization.2)createSepEpontrolglobalvarialization

go'serrorhandlingurturnserrorsasvalues,與Javaandpythonwhichuseexceptions.1)go'smethodensursexplitirorhanderling,propertingrobustcodebutincreasingverbosity.2)

AnefactiveInterfaceingoisminimal,clear and promotesloosecoupling.1)minimizeTheInterfaceForflexibility andeaseofimplementation.2)useInterInterfaceForabStractionToswaPimplementations withoutchangingCallingCode.3)

集中式錯誤處理在Go語言中可以提升代碼的可讀性和可維護性。其實現方式和優勢包括:1.將錯誤處理邏輯從業務邏輯中分離,簡化代碼。 2.通過集中處理錯誤,確保錯誤處理的一致性。 3.使用defer和recover來捕獲和處理panic,增強程序健壯性。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3 Linux新版
SublimeText3 Linux最新版

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

記事本++7.3.1
好用且免費的程式碼編輯器