golang会话变量不起作用。我做错了什么?

huangapple go评论150阅读模式
英文:

golang session variables not working. what am i doing incorrectly?

问题

我正在使用gorilla/sessions包来实现会话。相关的代码(或者至少我认为是唯一相关的部分)如下所示:

// 用于执行HTML代码的处理函数
func 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": "必须先登录",
})
}
}

// 根据需要提供文件,每当请求它们时
// 用于所有图像、js、css和其他静态文件
func 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": "用户未找到",
})
}
}

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("保存错误:", 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("已识别授权用户!")
return true
} else {
fmt.Println("检测到未授权用户!")
return false
}
}

return false

}

func main() {
//...

// 为游戏提供文件
http.HandleFunc("/", homeHandler)    
http.Handle("/ws", websocket.Handler(wsLobbyHandler))
http.HandleFunc("/lobby.html", lobbyHandler)
http.HandleFunc("/formlogin", loginHandler)
//...
//http.HandleFunc("/*.html", SourceHandler)
if err := http.ListenAndServeTLS(*addr, "cert.pem", "key.pem", nil); err != nil {
    log.Fatal("ListenAndServe:", err)
}

}

在我的HTML中:

当登录时,请求在loginHandler中处理

从数据库中正确识别用户并创建会话(通过createSession()),并将其放入cookie存储中。

但是,在重定向到lobby.html后,在loginHandler中

http.Redirect(w, req, "/lobby.html", http.StatusFound)

lobbyHandler中的验证不起作用。这是否与store.Save(...)修改标头有关?

我对Go和Web应用程序都非常陌生,所以我真的很希望得到反馈。

英文:

I am using the gorilla/sessions package to implement sessions. the relevant code (or at least what I think is the only relevant part) is as follows:

// Function handler for executing HTML code
func 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 files
func 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
}

func main() {
    //...
    
    // serving files for the game
    http.HandleFunc("/", homeHandler)    
    http.Handle("/ws", websocket.Handler(wsLobbyHandler))
    http.HandleFunc("/lobby.html", lobbyHandler)
    http.HandleFunc("/formlogin", loginHandler)
    //...
    //http.HandleFunc("/*.html", SourceHandler)
    if err := http.ListenAndServeTLS(*addr, "cert.pem", "key.pem", nil); err != nil {
        log.Fatal("ListenAndServe:", err)
    }
}`

in my html i have:

<form id="login_form" action="/formlogin" method="post">

When logging in, the request is handled within loginHandler

The user is identified correctly from the database and a session is created (via createSession()) and placed into the cookie store.

But after the redirect to lobby.html, back in loginHandler

http.Redirect(w, req, "/lobby.html", http.StatusFound)

the validation within lobbyHandler does not work. Does this have to do with the store.Save(...) altering the headers?

I'm very new to go, as well as web apps in general, so I would really appreciate feedback.

答案1

得分: 0

感谢评论,我能够偶然发现一个对我有效的类似搜索

session.Options = &sessions.Options{
    Path: "/lobby.html",
}

我需要确保cookie知道它们将被正确重定向的位置。

英文:

Thanks to the comments, i was able to stumble across a similar search that works for me.

session.Options = &sessions.Options{
    Path: "/lobby.html",
}

I needed to make sure the cookies know where they are going to be redirected properly.

huangapple
  • 本文由 发表于 2013年6月17日 06:29:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/17138331.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定