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

相关推荐
小吴编程之路2 小时前
MySQL 索引核心特性深度解析:从底层原理到实操应用
数据库·mysql
~莫子2 小时前
MySQL集群技术
数据库·mysql
咖啡の猫3 小时前
Redis桌面客户端
数据库·redis·缓存
what丶k3 小时前
如何保证 Redis 与 MySQL 数据一致性?后端必备实践指南
数据库·redis·mysql
石小千4 小时前
Ubuntu24.04安装Mysql8
运维·mysql
点点滴滴的记录4 小时前
Redis部署在Linux上性能高于Windows
linux·数据库·redis
lhj_loveFang_11054 小时前
Redis如何与数据库保持双写一致性
数据库·redis
闻哥4 小时前
深入Redis的RDB和AOF两种持久化方式以及AOF重写机制的分析
java·数据库·spring boot·redis·spring·缓存·面试
jolimark4 小时前
MySQL--》如何在MySQL中打造高效优化索引
android·mysql·adb
book123_0_994 小时前
【MySQL】MySQL函数之JSON_EXTRACT
android·mysql·json