如何向MiddlewareFunc传递参数?

4

我正在制作一个小型演示,试图解释基本的HTTP处理程序是如何工作的,并找到了以下示例:

package main

func 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 auth

func 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 middleware

func ApiHandler(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusOK)
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode("SUCCESS!")
    return
}

整体理解没问题,但是脑海中出现了两个问题:

  • 为什么这行代码secure.Use(auth.ValidateToken)不需要发送参数?
  • 如果我想要向该auth.ValidateToken函数发送额外的参数(例如字符串,与此标题进行比较而不是"SecretValue"),该如何实现?

先行致谢,我刚开始使用golang,希望学到更多。

1个回答

12

auth.Use 接受一个函数作为参数,而 auth.ValidateToken 是您传递的函数。 如果您想将参数发送到 auth.ValidateToken,可以编写一个接受该参数并返回一个中间件函数的函数,如下:

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"))

那个运行得非常好!我觉得有点困惑的是Go可以返回函数。我必须继续学习。 - Cas1337

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接