beego中session使用

session是在服务器端实现的一种用户和服务器之间认证的解决方案,beego 内置了 session 模块,目前 session 模块支持的后端引擎包括 memory、cookie、file、mysql、redis、couchbase、memcache、postgres,用户也可以根据相应的 interface 实现自己的引擎。

启动session,需要先在配置文件中如下配置:

sessionon = true

session初始化

var globalSessions *session.Manager

func InitSession(){

    sessionConfig := &session.ManagerConfig{
        CookieName:"gosessionid",
        EnableSetCookie: true,
        Gclifetime:3600,
        Maxlifetime: 3600,
        Secure: false,
        CookieLifeTime: 3600,
        ProviderConfig: "./tmp",
    }

    globalSessions,_ = session.NewManager("memory",sessionConfig)
    go globalSessions.GC()

设置 Session 的引擎,默认是 memory,目前支持还有 file是默认支持的。
如果要使用mysql、redis、couchbase、memcache、postgres等第三方引擎,需要提前导入包:

go get -u github.com/astaxie/beego/session/mysql

然后在main函数中导入该库,和数据库驱动引入是一样的:

import _ "github.com/astaxie/beego/session/mysql"

NewManager 函数的参数的函数如下所示

  • 引擎名字,可以是 memory、file、mysql 或 redis。
  • 一个JSON字符串,传入Manager的配置信息
  • cookieName: 客户端存储 cookie 的名字。
  • enableSetCookie,omitempty: 是否开启SetCookie,omitempty这个设置
  • gclifetime: 触发 GC 的时间。
  • maxLifetime: 服务器端存储的数据的过期时间
  • secure: 是否开启 HTTPS,在 cookie 设置的时候有 cookie.Secure 设置。
  • sessionIDHashFunc: sessionID 生产的函数,默认是 sha1 算法。
  • sessionIDHashKey: hash 算法中的 key。
  • cookieLifeTime: 客户端存储的 cookie 的时间,默认值是 0,即浏览器生命周期。
  • providerConfig: 配置信息,根据不同的引擎设置不同的配置信息
    详情的配置请查看beego标准库文档

session 有几个方便的方法:

SetSession(name string, value interface{})
GetSession(name string) interface{}
DelSession(name string)
SessionRegenerateID()
DestroySession()
session 操作主要有设置 session、获取 session、删除 session。

使用示例:

//登录验证完写入一个session
func (this *LoginController) Login() {
    log.Println("=================用户登录==================")
    this.TplName = "login/login.html"

    name := this.GetString("username")
    password := this.GetString("password")
    log.Printf("登录用户:%s 密码:%s",name,password)

    params := LoginParams{UserName: name, Password: password}
    if CheckLogin(params) {
        //登录验证通过,session记录,重定向链接到主页
        log.Printf("%s 登录成功!",name)
        this.SetSession("UserID", 1)
        this.Redirect("/", 302)
    }
}
//退出登录,删除sessionId
func (this *LoginController) Logout() {

    userid := this.GetSession("UserID")
    log.Println("sessionID为:", userid)
    if userid != nil {
        // UserID is set and can be deleted
        this.DelSession("UserID")
    }
}

你可能感兴趣的:(beego中session使用)