使用这个https://github.com/praveen001/go-passport
带有 passsport 中间件的路径:
app.Put("/api/auth/login", p.Authenticate("local", MyHandler))
护照认证功能:
// Authenticate calls `Strategy.Authenticate` method of registered strategies, and checks the `passport.Result` returned by it.
//
// The result is stored in the request context with `passport.CtxKey` as key.
//
func (p *Passport) Authenticate(name string, h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
s, ok := p.Options.strategies[name]
if !ok {
w.WriteHeader(404)
return
}
s.Authenticate(w, r, func(res *Result) {
res.StrategyName = name
ctx := context.WithValue(r.Context(), CtxKey, res)
h.ServeHTTP(w, r.WithContext(ctx))
})
}
}
因此,这会附加来自我的 auth 方法的响应并返回一个 http.HandleFunc,我可以自己定义(MyHandler)。
func MyHandler(w http.ResponseWriter, r *http.Request) {
// Where is the data attached from the Authenticate func?
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(401)
io.WriteString(w, `{"status":"ok"}`)
}
我不明白在哪里可以从Authenticatefunc 获取附加数据。评论说:“//结果存储在请求上下文中,passport.CtxKey作为键”。
我在r *http.Request.
30秒到达战场
相关分类