【发布时间】: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,你的评论帮我找到了答案,我很困惑。
-
很高兴我能帮上忙