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

时间:2017-01-26 14:58:15

标签: go negroni

我正在尝试在 Negroni 中间件处理程序中向请求上下文添加Gorilla会话,以便我可以在我的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.
}

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

1 个答案:

答案 0 :(得分:0)

Redirect语句正在接收原始请求,而不包含包含会话的新上下文。此处还需要使用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让我沿着正确的道路前进。