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

简介: 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)
}
相关文章
|
存储 Java Linux
Springboot 超简单实现在线预览,Word文档 doc、xlsx、pdf、txt等
Springboot 超简单实现在线预览,Word文档 doc、xlsx、pdf、txt等
3389 0
Springboot 超简单实现在线预览,Word文档 doc、xlsx、pdf、txt等
|
存储 项目管理 Python
数据导入与预处理-第4章-数据获取python读取docx文档(上)
数据导入与预处理-第4章-pandas数据获取docx文档 1.python读取docx文档概述 1.1 从Word文件获取数据 1.2 python-docx库介绍 1. Paragraph类 2. Table类
数据导入与预处理-第4章-数据获取python读取docx文档(上)
|
9月前
|
API
开源剪映小助手(capcut-mate)v3.0.22发布
CapCut Mate API 是开源免费的剪映草稿自动化工具,基于 FastAPI,支持独立部署。为大模型提供开箱即用的视频编辑 Skills,实现剪映核心功能全流程自动化,轻松生成专业视频。兼容 Coze/n8n,支持云渲染。
2020 1
|
10月前
|
人工智能 安全 JavaScript
小白零门槛上手:2026年OpenClaw(Clawdbot)一键部署接入WhatsApp教程
在AI智能体全民普及的2026年,OpenClaw(原Clawdbot,曾用名Moltbot)凭借开源免费、操作简单、场景适配广的核心优势,成为新手小白解锁AI自动化的首选工具。它无需复杂编程基础,就能实现文件处理、任务提醒、信息检索、跨平台协同等日常需求,更可无缝接入WhatsApp,让你通过手机聊天界面直接发送指令,实现“随时随地调用AI、指令直达响应”的便捷体验,适配跨境沟通、日常办公、个人管理等多元场景,尤其适合有跨境交流需求的新手群体。
1314 1
|
传感器 算法 自动驾驶
【卡尔曼滤波跟踪】基于卡尔曼滤波的二维目标跟踪(Matlab实现)
【卡尔曼滤波跟踪】基于卡尔曼滤波的二维目标跟踪(Matlab实现)
502 0
|
人工智能 监控 数据可视化
BISHENG下一代企业AI应用的“全能型“LLM软件
杭州奥零数据科技有限公司成立于2023年,专注于数据中台业务,维护开源项目AllData并提供商业版解决方案。AllData提供数据集成、存储、开发、治理及BI展示等一站式服务,支持AI大模型应用,助力企业高效利用数据价值。
|
Java Spring
Spring Boot的核心注解是哪个?他由哪几个注解组成的?
Spring Boot的核心注解是@SpringBootApplication , 他由几个注解组成 : ● @SpringBootConfiguration: 组合了- @Configuration注解,实现配置文件的功能; ● @EnableAutoConfiguration:打开自动配置的功能,也可以关闭某个自动配置的选项 ● @ComponentScan:Spring组件扫描
|
数据可视化 流计算 Python
Python创意爱心代码大全:从入门到高级的7种实现方式
本文分享了7种用Python实现爱心效果的方法,从简单的字符画到复杂的3D动画,涵盖多种技术和库。内容包括:基础字符爱心(一行代码实现)、Turtle动态绘图、Matplotlib数学函数绘图、3D旋转爱心、Pygame跳动动画、ASCII艺术终端显示以及Tkinter交互式GUI应用。每种方法各具特色,适合不同技术水平的读者学习和实践,是表达创意与心意的绝佳工具。
12253 0
|
人工智能 Dart IDE
SonarQube Server 10.8 发布,新增功能概览
SonarQube Server 10.8 发布,新增功能概览
683 5
SonarQube Server 10.8 发布,新增功能概览