我正在做一個(gè)小演示,試圖解釋一個(gè)基本的 HTTP 處理程序是如何工作的,我找到了以下示例:package mainfunc router() *mux.Router { router := mux.NewRouter() auth := router.PathPrefix("/auth").Subrouter() auth.Use(auth.ValidateToken) auth.HandleFunc("/api", middleware.ApiHandler).Methods("GET") return router}func main() { r := router() http.ListenAndServe(":8080", r)}package authfunc ValidateToken(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var header = r.Header.Get("secret-access-token") json.NewEncoder(w).Encode(r) header = strings.TrimSpace(header) if header == "" { w.WriteHeader(http.StatusForbidden) json.NewEncoder(w).Encode("Missing auth token") return } if header != "SecretValue" { w.WriteHeader(http.StatusForbidden) json.NewEncoder(w).Encode("Auth token is invalid") return } json.NewEncoder(w).Encode(fmt.Sprintf("Token found. Value %s", header)) next.ServeHTTP(w, r) })}package middlewarefunc ApiHandler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode("SUCCESS!") return}一切都可以理解,但我想到了兩個(gè)問(wèn)題:為什么不需要在此行中發(fā)送參數(shù):secure.Use(auth.ValidateToken)?如果我想向這個(gè)auth.ValidateToken函數(shù)發(fā)送一個(gè)額外的參數(shù),(例如,一個(gè)字符串,應(yīng)該比較這個(gè)頭而不是"SecretValue"),怎么做?在此先感謝,我對(duì)使用 golang 有點(diǎn)陌生,想了解更多。
1 回答

青春有我
TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超8個(gè)贊
auth.Use將函數(shù)作為參數(shù),并且auth.ValidateToken是您傳遞的函數(shù)。如果要向 發(fā)送參數(shù)auth.ValidateToken,可以編寫一個(gè)接受該參數(shù)的函數(shù),并返回一個(gè)中間件函數(shù),如下所示:
func GetValidateTokenFunc(headerName string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var header = r.Header.Get(headerName)
...
}
}
}
然后你可以這樣做:
auth.Use(auth.GetValidateTokenFunc("headerName"))
- 1 回答
- 0 關(guān)注
- 142 瀏覽
添加回答
舉報(bào)
0/150
提交
取消