dsaf32131 2013-06-16 22:29
浏览 48
已采纳

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

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条回答 默认 最新

  • dreamy1992 2013-06-17 12:15
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c