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.

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

报告相同问题?

悬赏问题

  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作