使用 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天前 | go · Go问答 · 版本迁移 · X.509 · Go 1.27 crypto/x509/pkix pkix.Name RDNSequence OID
- Go 1.27 pkix.Name 输出变了怎么兼容:未知 OID 不再总是十六进制
- 466浏览 收藏
-
- Golang · Go问答 | 1天前 | go · 安全 · 运行时 · Goroutine Go 1.27 runtime/secret 机密内存
- Go 1.27 runtime/secret 会不会传给新 goroutine:机密内存与平台边界
- 180浏览 收藏
-
- Golang · Go问答 | 1天前 | go · 性能排查 · 运行时 · Go 1.27 · 内存分配 Go 1.27 size-specialized malloc GOEXPERIMENT
- Go 1.27 小对象分配变快要不要关:size-specialized malloc 的收益与回退开关
- 395浏览 收藏
-
- Golang · Go问答 | 1天前 | go · TLS · 网络安全 · 版本迁移 · 证书链 · crypto/tls Go 1.27 TLS 1.3 ConnectionState.LocalCertificate PeerCertificates
- Go 1.27 的 TLS 连接证书怎么取:ConnectionState.LocalCertificate 不是对端证书
- 480浏览 收藏
-
- Golang · Go问答 | 2天前 | go · pprof · 并发排查 · goroutineleak runtime/pprof Go 1.27 Go 协程泄漏
- Go 1.27 goroutineleak 怎么看:能发现什么,为什么全局可达对象仍可能漏检
- 465浏览 收藏
-
- Golang · Go问答 | 2天前 | 并发 · go · pprof · 性能排查 · 可达性 goroutineleak goroutine 泄漏 runtime/pprof Go 1.27
- Go 1.27 goroutineleak 能查出哪些泄漏:全局变量为何会让 profile 漏报
- 351浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
-
- SuperCLUE
- SuperCLUE是权威的中文大语言模型综合评测基准,涵盖语言理解、知识应用、AI Agent智能体及安全性等12项核心能力。通过多轮对话与客观测试,定期发布榜单与技术报告,为模型研发、优化及行业选型提供科学依据。
- 107次使用
-
- C-Eval
- 深入了解C-Eval中文评估套件,涵盖52个学科与4级难度。本文详解其功能特点、Zero-shot/Few-shot使用方法及代码示例,助您全面评测LLM中文理解与泛化能力。
- 26次使用
-
- Gradio
- Gradio是一个用于构建机器学习和数据科学Web应用的开源Python库。支持快速创建交互界面,获Google、Meta等大厂青睐,适合模型演示、部署反馈及调试。
- 105次使用
-
- AutoGPT
- AutoGPT是基于GPT-4的开源AI代理平台,拥有超10万GitHub星标。本文介绍其低代码界面、自动化工作流功能、系统配置要求及安装步骤,助您高效部署和管理AI Agent。
- 110次使用
-
- Dataify
- Dataify是专注AI生态的一站式数据服务平台,整合全球住宅代理、多源数据采集API及高质量训练数据集。支持LLM训练、跨境电商及金融分析,解决数据孤岛难题,助力企业智能化转型。
- 11次使用
-
- GOLANG使用Context管理关联goroutine的方法
- 2022-12-28 193浏览
-
- 聊聊Go中的注释和godoc工具
- 2022-12-29 354浏览
-
- 聊聊Golang语言中的复数类型
- 2023-01-07 418浏览
-
- 浅析Golang中的浮点类型(float32和float64)
- 2022-12-23 161浏览
-
- 聊聊Golang中的整数类型
- 2022-12-24 209浏览

