Beego学习——实现用户登录登出

controller包

  user.go

import (
	"demo03.cn/models"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

type UserController struct {
	beego.Controller
}

func (c *UserController) Reg()  {

	resp :=make(map[string]interface{})
	defer c.RetData(resp)

	//获取前端传过来的json的数据
	_ = json.Unmarshal(c.Ctx.Input.RequestBody,&resp)
	//封装成结构体
	o := orm.NewOrm()
	user := models.User{}
	user.Name = resp["name"].(string)
	user.Password = resp["password"].(string)
	id,err :=o.Insert(&user)
	if err != nil{
		resp["errmsg"]="注册失败"
		return
	}
	resp["errmsg"]=fmt.Sprintf("注册成功,id:%d",id)
	c.SetSession("name",user.Name)
}

// 格式化数据 返回json格式
func (c *UserController) RetData(resp map[string]interface{}) {
	c.Data["json"] =resp
	c.ServeJSON()
}

  session.go

controller session.go

import (
	"demo03.cn/models"
	"encoding/json"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
)

type SessionController struct {
	beego.Controller
}

//TODO 获取Session
func (c *SessionController) GetSessionData()  {
	logs.Info("connect success")
	resp :=make(map[string]interface{})
	defer c.RetData(resp)

	user := models.User{}

	session := c.GetSession("name")
	if session!=nil {
		user.Name = session.(string)
		resp["msg"] = "获取成功"
		resp["data"] = user
	}else {
		resp["msg"] = "获取失败"
		logs.Info(user)
	}
}

//删除对应的Session
func (c *SessionController) DeleteSessionData()  {
	resp := make(map[string]interface{})
	defer c.RetData(resp)
	c.DelSession("name")
	resp["msg"]="删除成功"
}

// TODO 登录
func (c *SessionController) Login()  {
	resp := make(map[string]interface{})
	defer c.RetData(resp)

	//得到用户信息获取前端传递过来的json数据
	_ = json.Unmarshal(c.Ctx.Input.RequestBody,&resp)
	logs.Info(&resp)

	//判断是否合法
	if resp["name"] == nil || resp["password"] ==nil{
		resp["msg"]="用户名和密码不可以为空!"
		return
	}
	//与数据库匹配账号密码是否正确
	o := orm.NewOrm()
	user := models.User{Name:resp["name"].(string)}
	name := resp["name"].(string)
	qs := o.QueryTable("user")
	err := qs.Filter("name",name).One(&user)
	if err !=nil {
		resp["msg"]="数据错误"
		logs.Info("2222name=",resp["name"],"password:",resp["password"])
		return
	}
	if user.Password != resp["password"] {
		resp["msg"]="用户名或密码错误"
		logs.Info("3333name=",resp["name"],"password:",resp["password"])
		return
	}
	//添加Session
	c.SetSession("name",resp["name"])
	c.SetSession("user_id",user.Id)
	//返回json数据给前端
	resp["msg"]="登录成功"
}
func (c *SessionController) RetData(resp map[string]interface{}) {
	c.Data["json"] =resp
	c.ServeJSON()
}

models包

  userModel.go

import (
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
)

type User struct {
	Id       int    `json:"id"`
	Name string `json:"name"`
	Password string `json:"password"`
}

func init() {
	// 映射model数据
	orm.RegisterModel(new(User))
}

router包

  router.go

func init() {
	beego.Router("/user/session",&controllers.SessionController{},"get:GetSessionData;delete:DeleteSessionData")
	beego.Router("/user/sessions",&controllers.SessionController{},"post:Login")
	beego.Router("/user/users",&controllers.UserController{},"post:Reg")
}

main.go

import (
	_ "demo03.cn/routers"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/context"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	"net/http"
	"strings"
)
//

func main() {
	ignoreStaticPath()
	beego.Run()
}

func ignoreStaticPath()  {
	beego.InsertFilter("/",beego.BeforeRouter,TransparentStatic)
	beego.InsertFilter("/*",beego.BeforeRouter,TransparentStatic)
}

func TransparentStatic(ctx *context.Context){
	// 获取请求的url
	orpath := ctx.Request.URL.Path
	logs.Info("request url:",orpath)
	//如果请求url包含api字段,说明指令应该取消静态资源重定向
	if strings.Index(orpath,"user") >= 0{
		return
	}
	// 静态资源重定向
	//http.ServeFile(ctx.ResponseWriter,ctx.Request,"static/html"+ctx.Request.URL.Path)
	http.ServeFile(ctx.ResponseWriter,ctx.Request,"static/img/img")
}

func init() {
	// 设置数据库基本信息,相当于连接数据库
	_ = orm.RegisterDataBase("default", "mysql", beego.AppConfig.String("dataSource"), 30)
	// 生成表
	_ = orm.RunSyncdb("default", false, true)
}

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_52000204/article/details/120376356