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

相关推荐
IT规划师几秒前
Redis 核心机制 | 内存淘汰策略全解:8种策略、近似LRU采样、LFU计数器
redis·.net
索西引擎11 小时前
MySQL 进阶:视图、存储过程、存储函数与触发器
数据库·mysql
bksczm12 小时前
InnoDB 通用表空间与临时表空间详解
大数据·数据库·mysql
靠沿13 小时前
MySQL数据库进阶——存储过程和触发器
java·数据库·mysql
码少女14 小时前
MySQL--库与表的增删改查基础
java·数据库·mysql
打工的小王14 小时前
postgresql和mysql对比
数据库·mysql·postgresql
联犀16 小时前
ai时代复杂项目的golang项目如何更好的与ai共舞:monorepo+gozero
开发语言·人工智能·golang
codeejun17 小时前
每日一Go·MySQL-15、慢查询日志实战分析(从 0 到 1 实战排查慢 SQL)
sql·mysql·golang
Decay__19 小时前
SQLServer 监控体系构建 —— sql_exporter + Prometheus + Grafana 全栈实战
运维·数据库·sql·mysql·架构
飞奔的瓜牛20 小时前
Nacos 三节点集群部署手册:MySQL 持久化 + Nginx 负载均衡
mysql·nginx·负载均衡