第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

如何將參數(shù)傳遞給 MiddlewareFunc?

如何將參數(shù)傳遞給 MiddlewareFunc?

Go
胡子哥哥 2022-05-23 17:46:15
我正在做一個(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"))


查看完整回答
反對(duì) 回復(fù) 2022-05-23
  • 1 回答
  • 0 關(guān)注
  • 142 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)