使用 gorilla 会话时未保存 golang 中的会话变量
本篇文章给大家分享《使用 gorilla 会话时未保存 golang 中的会话变量》,覆盖了Golang的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。
问题内容
使用 gorilla 会话 Web 工具包时,不会跨请求维护会话变量。当我启动服务器并键入 localhost:8100/ 时,页面被定向到 login.html,因为会话值不存在。登录后,我在商店中设置会话变量,页面被重定向到 home.html。但是,当我打开一个新选项卡并键入 localhost:8100/ 时,该页面应该使用已存储的会话变量定向到 home.html,但该页面改为重定向到 login.html。以下是代码。
package main import ( "crypto/md5" "encoding/hex" "fmt" "github.com/gocql/gocql" "github.com/gorilla/mux" "github.com/gorilla/sessions" "net/http" "time" ) var store = sessions.NewCookieStore([]byte("something-very-secret")) var router = mux.NewRouter() func init() { store.Options = &sessions.Options{ Domain: "localhost", Path: "/", MaxAge: 3600 * 1, // 1 hour HttpOnly: true, } } func main() { //session handling router.HandleFunc("/", SessionHandler) router.HandleFunc("/signIn", SignInHandler) router.HandleFunc("/signUp", SignUpHandler) router.HandleFunc("/logOut", LogOutHandler) http.Handle("/", router) http.ListenAndServe(":8100", nil) } //handler for signIn func SignInHandler(res http.ResponseWriter, req *http.Request) { email := req.FormValue("email") password := req.FormValue("password") //Generate hash of password hasher := md5.New() hasher.Write([]byte(password)) encrypted_password := hex.EncodeToString(hasher.Sum(nil)) //cassandra connection cluster := gocql.NewCluster("localhost") cluster.Keyspace = "gbuy" cluster.DefaultPort = 9042 cluster.Consistency = gocql.Quorum session, _ := cluster.CreateSession() defer session.Close() //select query var firstname string stmt := "SELECT firstname FROM USER WHERE email= '" + email + "' and password ='" + encrypted_password + "';" err := session.Query(stmt).Scan(&firstname) if err != nil { fmt.Fprintf(res, "failed") } else { if firstname == "" { fmt.Fprintf(res, "failed") } else { fmt.Fprintf(res, firstname) } } //store in session variable sessionNew, _ := store.Get(req, "loginSession") // Set some session values. sessionNew.Values["email"] = email sessionNew.Values["name"] = firstname // Save it. sessionNew.Save(req, res) //store.Save(req,res,sessionNew) fmt.Println("Session after logging:") fmt.Println(sessionNew) } //handler for signUp func SignUpHandler(res http.ResponseWriter, req *http.Request) { fName := req.FormValue("fName") lName := req.FormValue("lName") email := req.FormValue("email") password := req.FormValue("passwd") birthdate := req.FormValue("date") city := req.FormValue("city") gender := req.FormValue("gender") //Get current timestamp and format it. sysdate := time.Now().Format("2006-01-02 15:04:05-0700") //Generate hash of password hasher := md5.New() hasher.Write([]byte(password)) encrypted_password := hex.EncodeToString(hasher.Sum(nil)) //cassandra connection cluster := gocql.NewCluster("localhost") cluster.Keyspace = "gbuy" cluster.DefaultPort = 9042 cluster.Consistency = gocql.Quorum session, _ := cluster.CreateSession() defer session.Close() //Insert the data into the Table stmt := "INSERT INTO USER (email,firstname,lastname,birthdate,city,gender,password,creation_date) VALUES ('" + email + "','" + fName + "','" + lName + "','" + birthdate + "','" + city + "','" + gender + "','" + encrypted_password + "','" + sysdate + "');" fmt.Println(stmt) err := session.Query(stmt).Exec() if err != nil { fmt.Fprintf(res, "failed") } else { fmt.Fprintf(res, fName) } } //handler for logOut func LogOutHandler(res http.ResponseWriter, req *http.Request) { sessionOld, err := store.Get(req, "loginSession") fmt.Println("Session in logout") fmt.Println(sessionOld) if err = sessionOld.Save(req, res); err != nil { fmt.Println("Error saving session: %v", err) } } //handler for Session func SessionHandler(res http.ResponseWriter, req *http.Request) { router.PathPrefix("/").Handler(http.FileServer(http.Dir("../static/"))) session, _ := store.Get(req, "loginSession") fmt.Println("Session in SessionHandler") fmt.Println(session) if val, ok := session.Values["email"].(string); ok { // if val is a string switch val { case "": { http.Redirect(res, req, "html/login.html", http.StatusFound) } default: http.Redirect(res, req, "html/home.html", http.StatusFound) } } else { // if val is not a string type http.Redirect(res, req, "html/login.html", http.StatusFound) } }
有人可以告诉我我做错了什么。提前致谢。
正确答案
首先: 你永远不应该使用 md5 来散列密码。[阅读这篇文章](http://www.codinghorror.com/blog/2012/04/speed- hashing.html)了解原因,然后使用 Go 的bcrypt 包。您还应该[参数化您的 SQL 查询](http://www.codinghorror.com/blog/2005/04/give-me-parameterized-sql-or- give-me-death.html),否则您可能会 遭受灾难性 的SQL 注入攻击。
无论如何:这里有几个问题需要解决:
- 您的会话没有“坚持”是因为您将其设置
Path
为/loginSession
- 因此当用户访问任何其他路径(即/
)时,会话对该范围无效。
您应该在程序初始化时设置会话存储并在那里设置选项:
var store = sessions.NewCookieStore([]byte("something-very-secret")) func init() { store.Options = &sessions.Options{ Domain: "localhost", Path: "/", MaxAge: 3600 * 8, // 8 hours HttpOnly: true, }
您可能会设置更具体的路径的原因是,如果登录的用户始终位于子路由中,例如/accounts
. 在你的情况下,这不是正在发生的事情。
我应该补充一点,Web Inspector 中的 Chrome 的“资源”选项卡(资源 > Cookie)对于调试此类问题非常有用,因为您可以看到 cookie 过期、路径和其他设置。
- 你也在检查
session.Values["email"] == nil
,这是行不通的。Go 中的空字符串只是""
,因为session.Values
是 amap[string]interface{}
,所以您需要将值输入到字符串中:
IE
if val, ok := session.Values["email"].(string); ok { // if val is a string switch val { case "": http.Redirect(res, req, "html/login.html", http.StatusFound) default: http.Redirect(res, req, "html/home.html", http.StatusFound) } } else { // if val is not a string type http.Redirect(res, req, "html/login.html", http.StatusFound) }
我们处理“不是字符串”的情况,所以如果会话不是我们所期望的(客户端修改了它,或者我们的程序的旧版本使用了不同的类型),我们会明确说明程序应该做什么。
-
保存会话时,您没有检查错误。
sessionNew.Save(req, res)
... 应该:
err := sessionNew.Save(req, res) if err != nil { // handle the error case }
-
SessionHandler
您应该在提供静态文件之前 获取/验证会话(但是,您正在以一种非常迂回的方式进行操作):func SessionHandler(res http.ResponseWriter, req *http.Request) { session, err := store.Get(req, "loginSession") if err != nil { // Handle the error } if session.Values["email"] == nil { http.Redirect(res, req, "html/login.html", http.StatusFound) } else { http.Redirect(res, req, "html/home.html", http.StatusFound) } // This shouldn't be here - router isn't scoped in this function! You should set this in your main() and wrap it with a function that checks for a valid session. router.PathPrefix("/").Handler(http.FileServer(http.Dir("../static/")))
}
本篇关于《使用 gorilla 会话时未保存 golang 中的会话变量》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

- 上一篇
- 使用反射获取指向值的指针

- 下一篇
- Golang 事件:用于插件架构的 EventEmitter / 调度程序
-
- Golang · Go问答 | 1年前 |
- 在读取缓冲通道中的内容之前退出
- 139浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 戈兰岛的全球 GOPRIVATE 设置
- 204浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何将结构作为参数传递给 xml-rpc
- 325浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何用golang获得小数点以下两位长度?
- 477浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何通过 client-go 和 golang 检索 Kubernetes 指标
- 486浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 将多个“参数”映射到单个可变参数的习惯用法
- 439浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 将 HTTP 响应正文写入文件后出现 EOF 错误
- 357浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 结构中映射的匿名列表的“复合文字中缺少类型”
- 352浏览 收藏
-
- Golang · Go问答 | 1年前 |
- NATS Jetstream 的性能
- 101浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何将复杂的字符串输入转换为mapstring?
- 440浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 相当于GoLang中Java将Object作为方法参数传递
- 212浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何确保所有 goroutine 在没有 time.Sleep 的情况下终止?
- 143浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 484次学习
-
- 笔灵AI生成答辩PPT
- 探索笔灵AI生成答辩PPT的强大功能,快速制作高质量答辩PPT。精准内容提取、多样模板匹配、数据可视化、配套自述稿生成,让您的学术和职场展示更加专业与高效。
- 24次使用
-
- 知网AIGC检测服务系统
- 知网AIGC检测服务系统,专注于检测学术文本中的疑似AI生成内容。依托知网海量高质量文献资源,结合先进的“知识增强AIGC检测技术”,系统能够从语言模式和语义逻辑两方面精准识别AI生成内容,适用于学术研究、教育和企业领域,确保文本的真实性和原创性。
- 41次使用
-
- AIGC检测-Aibiye
- AIbiye官网推出的AIGC检测服务,专注于检测ChatGPT、Gemini、Claude等AIGC工具生成的文本,帮助用户确保论文的原创性和学术规范。支持txt和doc(x)格式,检测范围为论文正文,提供高准确性和便捷的用户体验。
- 38次使用
-
- 易笔AI论文
- 易笔AI论文平台提供自动写作、格式校对、查重检测等功能,支持多种学术领域的论文生成。价格优惠,界面友好,操作简便,适用于学术研究者、学生及论文辅导机构。
- 50次使用
-
- 笔启AI论文写作平台
- 笔启AI论文写作平台提供多类型论文生成服务,支持多语言写作,满足学术研究者、学生和职场人士的需求。平台采用AI 4.0版本,确保论文质量和原创性,并提供查重保障和隐私保护。
- 41次使用
-
- 老师代码没有自动跟踪?
- 2023-03-07 439浏览
-
- c程序fork并等待golang进程状态
- 2023-03-05 262浏览
-
- GOLANG使用Context管理关联goroutine的方法
- 2022-12-28 193浏览
-
- 怎么用Golang将MySQL表转储为JSON
- 2023-03-07 188浏览
-
- Golang 检查字符串是否为有效路径?
- 2023-03-10 500浏览