我正在使用 gorilla/sessions 包来实现会话。相关代码(或至少我认为是唯一相关的部分)如下:// Function handler for executing HTML codefunc lobbyHandler(w http.ResponseWriter, req *http.Request) { if isLoggedIn := validateSession(w, req); isLoggedIn { lobbyTempl.Execute(w, req.Host) } else { homeTempl.Execute(w, map[string]string{ "loginErrors": "Must log in first", }) } }// Serves the files as needed, whenever they are requested// used for all images, js, css, and other static filesfunc sourceHandler(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, r.URL.Path[1:])}func loginHandler(w http.ResponseWriter, r *http.Request) { un, pw := r.FormValue("lUn"), r.FormValue("lPw") if usr := findUser(un, pw); usr != nil { if createSession(w, r) { http.Redirect(w, req, "/lobby.html", http.StatusFound) } } else { homeTempl.Execute(w, map[string]string{ "loginErrors": "User not found", }) }}func createSession(w http.ResponseWriter, r *http.Request) bool { session, _ := store.Get(r, sessionName) session.Values["isAuthorized"] = true if err := session.Save(r, w); err != nil { fmt.Println("saving error: ", err.Error()) return false } return true}func validateSession(w http.ResponseWriter, r *http.Request) bool { if session, err := store.Get(r, sessionName); err == nil { if v, ok := session.Values["isAuthorized"]; ok && v == true { fmt.Println("Authorized user identified!") return true } else { fmt.Println("Unauthorized user detected!") return false } } return false}在我的 html 中,我有:<form id="login_form" action="/formlogin" method="post">登录时,请求在 loginHandler 内处理从数据库中正确识别用户并创建会话(通过 createSession())并将其放入 cookie 存储。但是在重定向到 lobby.html 之后,回到 loginHandlerhttp.Redirect(w, req, "/lobby.html", http.StatusFound)lobbyHandler 中的验证不起作用。这是否与 store.Save(...) 改变标题有关?我很新,以及一般的网络应用程序,所以我非常感谢反馈。
- 1 回答
- 0 关注
- 205 浏览
添加回答
举报
0/150
提交
取消