2 回答

TA貢獻2003條經驗 獲得超2個贊
由于您正在檢查請求標頭中的令牌x-access-token
,因此需要在發送請求時添加相同的令牌。這可以在 Postman 中輕松完成,如下所示 -
我用過的路由器是 -
包主
func router() *mux.Router {
router := mux.NewRouter().StrictSlash(true)
secure := router.PathPrefix("/auth").Subrouter()
secure.Use(auth.JwtVerify)
secure.HandleFunc("/api", middleware.ApiHandler).Methods("GET")
return router
}
func main() {
r := router()
http.ListenAndServe(":8080", r)
}
我使用的中間件是 -
包授權
func JwtVerify(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var header = r.Header.Get("x-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
} else {
json.NewEncoder(w).Encode(fmt.Sprintf("Token found. Value %s", header))
}
next.ServeHTTP(w, r)
})
}
處理程序是 -
封裝中間件
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
}
- 2 回答
- 0 關注
- 168 瀏覽
添加回答
舉報