2 回答

TA貢獻1865條經(jīng)驗 獲得超7個贊
您的應(yīng)用程序的處理程序是http.DefaultServeMux。用另一個執(zhí)行代碼的處理程序包裝該處理程序:
// wrap returns an http.Handler that wraps another http.Handler
func wrap(h http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Before hook.
updateCookies(w, r)
h.ServeHTTP(w, r) // call the wrapped handler
// After hook.
// Nothing for now.
}
}
func main() {
http.Handle("/", http.FileServer(http.Dir("./web-files")))
http.HandleFunc("/auth/verify", verify)
http.HandleFunc("/auth/login", login)
http.HandleFunc("/auth/signup", signup)
http.ListenAndServe(":8080", wrap(http.DefaultServeMux))
}
我編寫代碼來包裝任意處理程序,因為可以輕松過渡到使用您自己的http.ServeMux:
func main() {
mux := http.NewServeMux()
mux.Handle("/", http.FileServer(http.Dir("./web-files")))
mux.HandleFunc("/auth/verify", verify)
mux.HandleFunc("/auth/login", login)
mux.HandleFunc("/auth/signup", signup)
http.ListenAndServe(":8080", wrap(mux))
}
任何包都可以在 http.DefaultServeMux 中注冊一個處理程序。創(chuàng)建自己的多路復(fù)用器可確保您完全控制應(yīng)用程序中運行的處理程序。

TA貢獻1877條經(jīng)驗 獲得超1個贊
http.Handle, http.HandleFunc, 和http.ListenAndServe(nil作為第二個參數(shù)),http.DefaultServeMux用于將請求路由到它們各自的處理程序。
http.ListenAndServe僅當(dāng)傳遞給它的第二個參數(shù)是時才使用默認 mux nil。如果提供了非 nil 參數(shù),那么它將使用該參數(shù)而不是默認的 mux 來處理傳入的請求。
鑒于http.ListenAndServe第二個參數(shù)的類型是http.Handler接口,您可以簡單地將updateCookiestohttp.ListenAndServe作為第二個參數(shù)傳遞(盡管您必須將其顯式轉(zhuǎn)換為http.HandlerFunc),然后修改updateCookies為,最后將 thew和 the傳遞r給默認多路復(fù)用器。
func updateCookies(w http.ResponseWriter, r *http.Request) {
// ... [your original cookie code] ...
http.DefaultServeMux.ServeHTTP(w, r)
}
// ...
http.ListenAndServe(":8080", http.HandlerFunc(updateCookies))
- 2 回答
- 0 關(guān)注
- 95 瀏覽
添加回答
舉報