Beego利用Session实现简单的登录验证

首先需要在框架中开启Session模块,可以通过写入app.conf配置,也可以通过入口函数(main.go)配置,我这里选择后者:

package main

import (
	"github.com/astaxie/beego"
	_ "testbeego/routers"
)

func main() {
	beego.BConfig.WebConfig.Session.SessionOn = true				//开启Session模块
	beego.BConfig.WebConfig.Session.SessionGCMaxLifetime = 86400	//设置Session有效期,单位秒
	beego.Run()
}

然后创建一个base.go并创建一个用于验证或公共方法的基类控制器BaseController,在此控制器中将验证方法写入Prepare函数中,注意不要写入init中,因为init只会在初次引用时执行一次,而Prepare会在每次调用中都执行一次,Session获取可以使用GetSession来实现,具体逻辑如下:

package controllers

import (
	"github.com/astaxie/beego"
)

type BaseController struct {
	beego.Controller
}

func (c *BaseController) Prepare() {
	userId := c.GetSession("userId")
	if userId == nil{
		c.Ctx.Redirect(302,"/login")		//若Session中无用户ID则302重定向至登陆页面
	}
	c.Data["userId"] = userId
}

然后我们要在需要验证是否登录的控制器中继承此基类控制器即可:

package controllers

import (
	"github.com/astaxie/beego/orm"
)

type IndexController struct {
	BaseController
}

func (c *IndexController) Index(){
	c.TplName = "index.html"
}

当然我们需要在登录后设置Session,使用SetSession即可:

c.SetSession("userId",Id)
发布了29 篇原创文章 · 获赞 1 · 访问量 7830

猜你喜欢

转载自blog.csdn.net/qq_38280150/article/details/102458999