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

标签 go negroni

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

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

最佳答案

Redirect 语句正在接收原始请求,但没有包含 session 的新上下文。这里还需要使用 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让我走上正确的道路。

关于go - Negroni:将上下文从中间件传递到处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41876310/

相关文章:

go - 在 Negroni 下找不到路由时提供索引文件

go - Negroni 在请求完成后继续调用其他处理程序

Go - 组合 cmd.StdoutPipe 和 Cmd.StderrPipe

go - Redis 和 Go 中 MongoDB id 的布隆过滤器

golang定时器从零开始重新计算

go - gofmt 重写规则可以删除冗余参数类型吗?

go - 使用 Go/Negroni/Gorilla Mux 从静态 url 提供文件

go - axios 不发送 POST 到 golang api

algorithm - html模板中的golang乘法算法

go - negroni 中不同路由的不同中间件