【问题标题】:Negroni: passing context from middleware to handlersNegroni:将上下文从中间件传递给处理程序
【发布时间】:2017-01-26 14:58:14
【问题描述】:

我正在尝试将 Gorilla Session 添加到 Negroni 中间件处理程序的 Request Context 中,以便我可以在我的 Gorilla Mux 处理程序中访问它。这是我的代码的精简版:

// 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.
}

希望这是有道理的。谁能指出我做错了什么?

【问题讨论】:

  • 您是否检查过store.Get 是否返回*sessions.Session
  • 谢谢@jmaloney,你的评论帮我找到了答案,我很困惑。
  • 很高兴我能帮上忙

标签: go negroni


【解决方案1】:

重定向语句正在接收原始请求,但没有包含会话的新上下文。这里也需要用到WithContext(ctx)函数:

// 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))
}

感谢@jmaloney 让我走上正确的道路。

【讨论】:

  • 有效,但不建议对WithValue 使用字符串键。根据文档:godoc.org/net/http#Request.WithContext
  • 提供的键必须是可比较的,并且不应该是字符串类型或任何其他内置类型,以避免使用上下文的包之间的冲突。 WithValue 的用户应该为键定义自己的类型。为避免在分配给 interface{} 时进行分配,上下文键通常具有具体类型 struct{}。或者,导出的上下文键变量的静态类型应该是指针或接口。)
猜你喜欢
  • 1970-01-01
  • 2011-07-26
  • 1970-01-01
  • 2015-05-12
  • 2016-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-30
相关资源
最近更新 更多