dtd58256 2017-01-26 06:58
浏览 35
已采纳

Negroni:将上下文从中间件传递给处理程序

I'm trying to add a Gorilla Session to the Request Context in a Negroni middleware handler so that I can access it in my Gorilla Mux handlers. Here's a stripped down version of my code:

// Session Middleware function
func sessMid(w http.ResponseWriter, r *http.Request, next 
http.HandlerFunc) {
  ctx := r.Context()
  s, _ := store.Get(r, "user") // store is a CookieStore
  ctx = context.WithValue(ctx, "example", s)

  if !loggedIn() {
    http.Redirect(w, r, "/login", http.StatusFound)
  }

  next(w, r.WithContext(ctx))
}

// Page handler
func pgHandler(w http.ResponseWriter, r *http.Request) {
  ctx := r.Context()
  s, ok := ctx.Value("example").(*sessions.Session)
  // ok returns false here, meaning that the session was not returned successfully.
}

Hopefully that makes sense. Can anyone point me to what I'm doing wrong?

  • 写回答

1条回答 默认 最新

  • dongpian6319 2017-01-27 00:04
    关注

    The Redirect statement is receiving the original request without the new context that contains the session. The WithContext(ctx) function needs to be used here as well:

    // Session Middleware function
    func sessMid(w http.ResponseWriter, r *http.Request, next 
    http.HandlerFunc) {
      ctx := r.Context()
      s, _ := store.Get(r, "user") // store is a CookieStore
      ctx = context.WithValue(ctx, "example", s)
    
      if !loggedIn() {
        // Make sure to add the context to the request sent in the Redirect
        http.Redirect(w, r.WithContext(ctx), "/login", http.StatusFound)
      }
    
      next(w, r.WithContext(ctx))
    }
    

    Thanks to @jmaloney for sending me down the right path.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部