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

相关推荐
布朗克1683 分钟前
Go 入门到精通-27-泛型编程
开发语言·golang·xcode·泛型编程
名字还没想好☜13 分钟前
Go 用 errgroup 管理并发子任务:错误收敛、取消传播与限流
开发语言·后端·golang·go·并发
数据库小学妹15 分钟前
MySQL在线DDL实战:ALGORITHM三种算法对比+gh-ost变更管理SOP
mysql·dba·数据库运维·在线ddl·mdl锁·sql变更管理
海兰23 分钟前
【高速缓存】RedisVL 指南:从向量搜索到 AI 应用落地
人工智能·redis
weixin_7275356225 分钟前
双Token认证体系深度拆解:Spring Security + JWT + Redis
redis·spring·wpf
Ethan01071 小时前
隔离级别管读,乐观锁管写——RC/RR 与写冲突的本质
mysql
熊文豪2 小时前
【金仓数据库征文】不装中间件的 MySQL→金仓在线迁移,mysql_fdw 全流程,和一个差点漏掉的 emoji
数据库·mysql·中间件·电科金仓
C++、Java和Python的菜鸟2 小时前
第5章 后端Web基础 (MySQL基础)
前端·mysql·adb
zhouhui0013 小时前
AI帮我写了个Spring Boot校验,线上漏掉了这组边界条件
java·spring boot·redis·ai编程
吃饱了得干活3 小时前
扫码登录如何实现?从原理到实战
java·spring boot·redis