我正在制作一个小型演示,试图解释基本的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,希望学到更多。