为了账号安全,请及时绑定邮箱和手机立即绑定

基于http中间件访问数据

基于http中间件访问数据

Go
长风秋雁 2022-07-11 14:57:24
使用这个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.
查看完整描述

1 回答

?
30秒到达战场

TA贡献1828条经验 获得超6个赞

http.Request对象有一个Context()为您提供上下文的方法。您可以通过它访问密钥。

例如

ctx := r.Context()
value := ctx.Value(passport.CtxKey)


查看完整回答
反对 回复 2022-07-11
  • 1 回答
  • 0 关注
  • 131 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号