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

相关推荐
一只小李郁vickie1 小时前
mysql 开启压缩传输3402条数据2.1秒压缩到毫秒级
数据库·mysql
码士集团小青1 小时前
从对标 Java 到对标 Go:Native AOT 的“无痛化“之路,走到哪一站了?
golang
右耳朵猫AI1 小时前
Go周刊2026W36 | Go 1.27.1 发布、TinyGo 0.42、HTTP/2 原生迁入 net/http、quic-go 0.62
redis·http·golang
前端兰博2 小时前
04-数据库-MySQL
后端·mysql
这个DBA有点耶2 小时前
COUNT慢不是因为用了*,是这5个原因——1000万行数据实测+执行计划深度解析
数据库·mysql·算法
kyrie_sakura3 小时前
MySQL数据库学习笔记2--系统函数(分组,单行,窗口函数)
数据库·学习·mysql
大牧师4 小时前
TypeORM 入门教程
后端·sql·mysql·orm·nest·typeorm
oliver_sys_log4 小时前
绕过 Yearning 查询体验限制:我做了一个 DataGrip 只读 SQL 代理
后端·mysql
山岚的运维笔记5 小时前
mysql 专业笔记 -- 第 17 章:连接:连接三个具有相同名称 ID 的表
运维·数据库·笔记·后端·学习·mysql·dba
bksczm6 小时前
从 “什么是 MySQL“ 到库与表的完整操作(MySQL基础篇)
linux·数据库·mysql