5 ZH_Session
Lunny Xiao edited this page 2019-11-27 09:08:08 +08:00
This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

Session 是一个 Tango 的 session 中间件.

后台

当前Session支持如下几种后台进行Session内容的存储:

  • Memory - 将Session保存在内存中这个是默认值
  • Redis - 使用redis服务器进行Session保存
  • Ledis - 使用ledis服务器进行Session保存
  • nodb - 使用nodb文件来保存Session

注意如果使用永久存储并且Session里面存储了结构体应在程序启动时进行结构体的gob注册

安装

go get gitea.com/tango/session

例子

package main

import (
    "gitea.com/lunny/tango"
    "gitea.com/tango/session"
)

type SessionAction struct {
    session.Session
}

func (a *SessionAction) Get() string {
    a.Session.Set("test", "1")
    return a.Session.Get("test").(string)
}

func main() {
    o := tango.Classic()
    o.Use(session.New(session.Options{
        MaxAge:time.Minute * 20,
        }))
    o.Get("/", new(SessionAction))
}

如果使用其它后台,则:

func main() {
    o := tango.Classic()
    o.Use(session.New(session.Options{
        MaxAge:time.Minute * 20,
        Store: redistore.New(Options{
			Host:    "127.0.0.1",
			DbIndex: 0,
			MaxAge:  30 * time.Minute,
		},
        }))
    o.Get("/", new(SessionAction))
}