dtd58256 2017-01-26 14: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 08: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.

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

报告相同问题?

悬赏问题

  • ¥15 yolov8边框坐标
  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真