英文:
Negroni: passing context from middleware to handlers
问题
我正在尝试将 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 是一个 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 返回 false,意味着会话未成功返回。
}
希望这样能清楚明白。有人能指出我做错了什么吗?
英文:
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
得分: 3
重定向语句接收到的是不包含会话的新上下文的原始请求。在这里也需要使用WithContext(ctx)
函数:
// 会话中间件函数
func sessMid(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
ctx := r.Context()
s, _ := store.Get(r, "user") // store 是一个 CookieStore
ctx = context.WithValue(ctx, "example", s)
if !loggedIn() {
// 确保将上下文添加到重定向中发送的请求中
http.Redirect(w, r.WithContext(ctx), "/login", http.StatusFound)
}
next(w, r.WithContext(ctx))
}
感谢@jmaloney给我指明了正确的方向。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论