整合dxvgef/session实现Session
使用dxvgef/session
包实现数据存储于Redis的Session功能:
- package main
- import (
- "github.com/dxvgef/httpdispatcher"
- "net/http"
- "log"
- "github.com/dxvgef/sessions"
- "time"
- )
- //session管理器实例
- var SessionManager *sessions.SessionManager
- func main() {
- var err error
- //获得一个调度器的实例化对象
- var dispatcher = httpdispatcher.New()
- //设置参数并获得session管理器实例
- SessionManager, err = sessions.NewSessions(&sessions.Config{
- CookieName: "sessionid",
- HttpOnly: true,
- Path: "/",
- MaxAge: 120,
- IdleTime: time.Duration(20) * time.Minute,
- Secure: false,
- RedisAddr: "127.0.0.1:6379",
- RedisDB: 0,
- RedisPassword: "",
- RedisKeyPrefix: "sess",
- Key: "key",
- })
- if err != nil {
- log.Println(err.Error())
- return
- }
- //在入口路由里传入session处理器
- router := dispatcher.Router.GROUP("", func(ctx *httpdispatcher.Context) error {
- //更新session空闲时间
- err := SessionManager.UpdateIdleTime(ctx.Request, ctx.ResponseWriter)
- if err != nil {
- return ctx.Event(err)
- }
- //继续执行下一个处理器
- return ctx.Next(true)
- })
- //在路由组中定义GET路由测试session读写
- router.GET("/", func(ctx *httpdispatcher.Context) error {
- //使用session
- session, err := SessionManager.UseSession(ctx.Request, ctx.ResponseWriter)
- if err != nil {
- return ctx.Event(err)
- }
- //在session中写入数据
- if err := session.Set("test", "ok"); err != nil {
- return ctx.Event(err)
- }
- //从session中读取数据
- if test, err := session.Get("test").String(); err != nil {
- return ctx.Event(err)
- } else {
- log.Println(test)
- }
- return nil
- })
- svr := &http.Server{
- Addr: ":8080",
- Handler: dispatcher,
- }
- if err := svr.ListenAndServe(); err != nil {
- log.Fatal(err.Error())
- }
- }