在 Gorilla 会话实现中,不会跨请求维护会话变量。登录并设置会话变量后,新选项卡应该维护会话,但用户会被重定向到登录页面。
<code class="go">sessionNew.Save(req, res)</code>
此代码丢失错误sessionNew.Save() 的处理。如果保存过程失败,该错误将被忽略,从而导致意外行为。应更新为:
<code class="go">err := sessionNew.Save(req, res) if err != nil { // Handle the error }</code>
会话路径设置为“/loginSession”,这将会话的范围限制为仅该特定路径。这可能会导致混乱,因为访问其他路由的用户将无法访问该会话。为了确保会话在所有路由上可用,路径应设置为“/”。
在 SessionHandler 中,会话检查在提供静态文件后执行。这可能会导致问题,因为静态文件是在验证会话之前提供的。应在提供任何内容之前执行会话检查。
<code class="go">package main import ( "crypto/md5" "encoding/hex" "fmt" "github.com/gocql/gocql" "github.com/gorilla/mux" "github.com/gorilla/sessions" "net/http" "time" ) var store = sessions.NewCookieStore([]byte("something-very-secret")) var router = mux.NewRouter() func init() { store.Options = &sessions.Options{ Domain: "localhost", Path: "/", MaxAge: 3600 * 8, // 8 hours HttpOnly: true, } } func main() { //session handling router.HandleFunc("/", sessionHandler) router.HandleFunc("/signIn", signInHandler) router.HandleFunc("/signUp", signUpHandler) router.HandleFunc("/logOut", logOutHandler) http.Handle("/", router) http.ListenAndServe(":8100", nil) } //handler for signIn func signInHandler(res http.ResponseWriter, req *http.Request) { // Get the session session, err := store.Get(req, "loginSession") if err != nil { // Handle the error } // Set session values session.Values["email"] = req.FormValue("email") session.Values["name"] = req.FormValue("password") // Save the session err = session.Save(req, res) if err != nil { // Handle the error } } //handler for signUp func signUpHandler(res http.ResponseWriter, req *http.Request) { // ... } //handler for logOut func logOutHandler(res http.ResponseWriter, req *http.Request) { // Get the session session, err := store.Get(req, "loginSession") if err != nil { // Handle the error } // Save the session (with updated values) err = session.Save(req, res) if err != nil { // Handle the error } } //handler for Session func sessionHandler(res http.ResponseWriter, req *http.Request) { // Get the session session, err := store.Get(req, "loginSession") if err != nil { // Handle the error } // Check if the session is valid if session.Values["email"] == nil { http.Redirect(res, req, "html/login.html", http.StatusFound) } else { http.Redirect(res, req, "html/home.html", http.StatusFound) } }</code>
以上是为什么我的 Golang 会话变量没有保存在 Gorilla 会话中?的详细内容。更多信息请关注PHP中文网其他相关文章!