go - 基于http中间件访问数据
问题描述
使用这个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"}`)
}
我不明白在哪里可以从Authenticate
func 获取附加数据。评论说:“//结果存储在请求上下文中,passport.CtxKey
作为键”。
我在r *http.Request
.
解决方案
该http.Request
对象有一个Context()
为您提供上下文的方法。您可以通过它访问密钥。
例如
ctx := r.Context()
value := ctx.Value(passport.CtxKey)
推荐阅读
- c# - 存储库模式的更新概念
- python - 如何为 Python 安装 SHAP (Shapley)
- java - 在不覆盖第一个元素的情况下设置 RecyclerView Header
- python - 无法解析这个 json 文件
- sql - 如何根据 ReportingMonth 值计算 StartDate 和 EndDate
- entity-framework - EF core 2.1 升级 Null 引用异常,即使在检查 not null
- c# - 如何对 Google Drive Api 进行服务器到服务器身份验证?
- excel - SAS 日期格式 (mmddyy10.) 在 excel 数据透视表中显示为 ddmm1958
- npm - npm run bundle 有什么作用?
- sql - 更新已在同一脚本中添加的列