【发布时间】:2017-08-21 10:02:14
【问题描述】:
我正在使用 Go 会话管理:
"github.com/gorilla/sessions"
以下代码的问题是与 CookieStore 关联的会话没有在处理程序之间共享,我需要它来这样做。
处理程序"/authorize" 将值保存到会话中,然后重定向到另一个处理程序"/thankyou",但该处理程序在会话中看不到该值。
我已验证会话在原始处理程序 "/authorize" 中确实具有新值。
import (
"github.com/gorilla/sessions"
)
var (
cookieStore *sessions.CookieStore
storeGUID string
sessionGUID string
)
func init() {
storeGUID = "{random-string}"
sessionGUID = "{random-string}"
cookieStore = sessions.NewCookieStore([]byte(storeGUID))
}
mux.HandleFunc("/authorize", func(w http.ResponseWriter, r *http.Request) {
var sess *sessions.Session
sess, err := cookieStore.Get(r, sessionGUID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
sess.Values["authMode"] = "Authorized"
if err := sess.Save(r, w); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Redirect to "/thankyou"
authorizeURL := r.URL.String()
thankyouRedirectURL := strings.Replace(authorizeURL, "authorize", "thankyou", 1)
defer http.Redirect(w, r, thankyouRedirectURL, http.StatusFound)
}
mux.HandleFunc("/thankyou", func(w http.ResponseWriter, r *http.Request) {
var sess *sessions.Session
sess, err := cookieStore.Get(r, sessionGUID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
var sval interface{}
var authMode string
sval = sess.Values["authMode"]
if authMode, ok := sval.(string); !ok {
err := errors.New("Missing \"authSess\" in session.")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
【问题讨论】: