golang session实现库 支持cookie, redis,mysql等多种存储方式

golang中官方是不支持session的, 如果想要实现session则需要自己动手来实现,或者使用第三方的go-session实现库, 今天就给大家介绍一个go语言的第三方session实现库 go-sessions,支持 的存储方式有 cookie, file, redis, mysql等众多的存储。

使用示例:

Go 复制代码
import (
		"net/http"
		"github.com/gorilla/sessions"
	)

	// Note: Don't store your key in your source code. Pass it via an
	// environmental variable, or flag (or both), and don't accidentally commit it
	// alongside your code. Ensure your key is sufficiently random - i.e. use Go's
	// crypto/rand or securecookie.GenerateRandomKey(32) and persist the result.
	var store = sessions.NewCookieStore([]byte(os.Getenv("SESSION_KEY")))

	func MyHandler(w http.ResponseWriter, r *http.Request) {
		// Get a session. We're ignoring the error resulted from decoding an
		// existing session: Get() always returns a session, even if empty.
		session, _ := store.Get(r, "session-name")
		// Set some session values.
		session.Values["foo"] = "bar"
		session.Values[42] = 43
		// Save it before we write to the response/return from the handler.
		err := session.Save(r, w)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	}

Github项目地址:

GitHub - tekintian/go-sessions: go语言里面的Sessions实现库, 支持众多的Session存储方式,cookie, redis, mysql等。 Package gorilla/sessions provides cookie and filesystem sessions and infrastructure for custom session backends.go语言里面的Sessions实现库, 支持众多的Session存储方式,cookie, redis, mysql等。 Package gorilla/sessions provides cookie and filesystem sessions and infrastructure for custom session backends. - tekintian/go-sessionshttps://github.com/tekintian/go-sessions

相关推荐
这个DBA有点耶3 小时前
热点行更新:秒杀场景下一条UPDATE语句的锁等待与性能优化
数据库·sql·mysql·性能优化·database·dba
FfHUCisI3 小时前
循环链表(Circular Linked List)
golang
Wang's Blog4 小时前
Go-Zero项目开发30: 微服务配置中心的设计与实现
开发语言·微服务·golang·go-zero
冰暮流星4 小时前
mysql之新建表及对表的查询
android·数据库·mysql
名字还没想好☜5 小时前
Go for-range 循环变量陷阱:goroutine 里全打印同一个值(Go 1.22 前后差异)
开发语言·后端·golang·go
Bug收容所5 小时前
12305项目学习day5
java·spring boot·redis·mysql·spring·rocketmq
智码看视界6 小时前
Day33-数据层 × 中间件AI化篇:Redis缓存经典问题-击穿、穿透、雪崩的终极解决方案
数据库·redis·缓存·中间件·穿透·雪崩·击穿
会编程的土豆6 小时前
功能详解 01 · 用户注册:从表单到数据库一行
开发语言·数据库·后端·mysql·golang
溜达的大象6 小时前
Prometheus怎么监控MySQL?mysqld_exporter部署与告警教程
mysql·adb·prometheus
go不是csgo6 小时前
从模板到五道 LeetCode:完全背包的 Golang 教学笔记
笔记·leetcode·golang