While using Gorilla Sessions web toolkit, session variables are not retained across requests. When the server launches and users visit localhost:8100/, they are directed to login.html because session values do not exist. Upon login, session variables are stored, and users are redirected to home.html. However, opening a new tab and inputting localhost:8100/ directs users to login.html instead of home.html as expected, despite the presence of session variables.
Several issues arise in the provided code:
Relevant Code Snippets (after addressing the issues):
// Set session options
store.Options = &sessions.Options{
Domain: "localhost",
Path: "/",
MaxAge: 3600 * 8, // 8 hours
HttpOnly: true,
}
// Session handling in `SessionHandler`
func SessionHandler(res http.ResponseWriter, req *http.Request) {
session, err := store.Get(req, "loginSession")
if err != nil {
// Handle the error
}
// Check for a valid session
if session.Values["email"] == nil {
http.Redirect(res, req, "html/login.html", http.StatusFound)
} else {
http.Redirect(res, req, "html/home.html", http.StatusFound)
}
}
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3