首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Negroni:将上下文从中间件传递给处理程序

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

Stack Overflow用户
提问于 2017-01-26 14:58:14
回答 1查看 2.9K关注 0票数 2

我正在尝试在Negroni中间件处理程序中向请求上下文添加一个Gorilla会话,以便我可以在Gorilla处理程序中访问它。下面是我的代码的简化版本:

代码语言:javascript
复制
// 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.
}

希望这是合理的。有人能告诉我我做错了什么吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-01-27 08:04:49

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

代码语言:javascript
复制
// 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把我送上了正确的道路。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41876310

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档