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

相关推荐
xiaoqiMikko9 小时前
Redis 实战(三):持久化出错 —— fork 失败、磁盘写满、AOF 膨胀与损坏,逐个复现(6.2.4)
redis·后端
GreatSQL9 小时前
GreatSQL 8.0回流MySQL 5.7主从复制中断分析排查过程
mysql
IT规划师9 小时前
面试中被嘲笑Token放在redis里,该如何应对?
redis·面试
数据库小学妹9 小时前
MySQL磁盘IO瓶颈:iostat与刷脏fsync
数据库·mysql·性能优化
皓月盈江10 小时前
GO使用Gin框架实现模板定义、解析与渲染
linux·golang·go·gin·定义模板·解析模板·渲染模板
Umi·10 小时前
MySQL之DQL使用实例
数据库·mysql
利威尔xu10 小时前
万字详解|Go 进阶(五):sync 包底层:Mutex 自旋 4 次转饥饿,WaitGroup 漏 1 个 Done 挂起 3000 goroutine
后端·golang·并发编程·源码分析·sync
贾公子11 小时前
检测结果怎么落库——表结构、状态机与三类对账
后端·mysql
z06.11 小时前
Linux系统中MySQL的安装
linux·mysql