conf>app.conf 文件添加一下参数
copyrequestbody=true
sessionon =true
routers>router.go 文件添加初始化路由
func init() {
///api/v1.0/areas
// beego.Router("/api/v1.0/areas", &controllers.AreaController{},"get:GetArea")
beego.Router("api/v1.0/areas", &controllers.LAreaControllers{}, "get:GetArea")
//TODO /api/v1.0/session
//TODO /api/v1.0/houses/index
beego.Router("/api/v1.0/session",&controllers.SessionController{},"get:GetSessionData;delete:DeleteSessionData")
beego.Router("/api/v1.0/sessions",&controllers.SessionController{},"post:Login")
beego.Router("/api/v1.0/houses/index",&controllers.HouseIndexController{},"get:GetHouseIndex")
beego.Router("/api/v1.0/users",&controllers.UserController{},"post:Reg")
}
models>recode.go 错误代码编码
package models
const (
RECODE_OK = "0"
RECODE_DBERR = "4001"
RECODE_NODATA = "4002"
RECODE_DATAEXIST = "4003"
RECODE_DATAERR = "4004"
RECODE_SESSIONERR = "4101"
RECODE_LOGINERR = "4102"
RECODE_PARAMERR = "4103"
RECODE_USERERR = "4104"
RECODE_ROLEERR = "4105"
RECODE_PWDERR = "4106"
RECODE_REQERR = "4201"
RECODE_IPERR = "4202"
RECODE_THIRDERR = "4301"
RECODE_IOERR = "4302"
RECODE_SERVERERR = "4500"
RECODE_UNKNOWERR = "4501"
)
var recodeText = map[string]string{
RECODE_OK: "成功",
RECODE_DBERR: "数据库查询错误",
RECODE_NODATA: "无数据",
RECODE_DATAEXIST: "数据已存在",
RECODE_DATAERR: "数据错误",
RECODE_SESSIONERR: "用户未登录",
RECODE_LOGINERR: "用户登录失败",
RECODE_PARAMERR: "参数错误",
RECODE_USERERR: "用户不存在或未激活",
RECODE_ROLEERR: "用户身份错误",
RECODE_PWDERR: "密码错误",
RECODE_REQERR: "非法请求或请求次数受限",
RECODE_IPERR: "IP受限",
RECODE_THIRDERR: "第三方系统错误",
RECODE_IOERR: "文件读写错误",
RECODE_SERVERERR: "内部错误",
RECODE_UNKNOWERR: "未知错误",
}
func RecodeText(code string)string {
str,ok := recodeText[code]
if ok {
return str
}
return RecodeText(RECODE_UNKNOWERR)
}
controllers>User.go 用户注册
package controllers
import (
"encoding/json"
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
"lovehome/models"
)
type UserController struct {
beego.Controller
}
func (c *UserController) Get() {
c.Data["Website"] = "beego.me"
c.Data["Email"] = "astaxie@gmail.com"
c.TplName = "index.tpl"
}
func (c *UserController) Reg() {
resp :=make(map[string]interface{})
defer c.RetData(resp)
//TODO 获取前端传过来的json的数据
json.Unmarshal(c.Ctx.Input.RequestBody,&resp)
//beego.Info(resp)
//TODO 封装成结构体
o := orm.NewOrm()
user := models.User{}
user.Mobile = resp["mobile"].(string)
user.Name = resp["mobile"].(string)
user.Password_hash = resp["password"].(string)
id,err :=o.Insert(&user)
if err != nil{
resp["errno"]=models.RECODE_NODATA
resp["errmsg"]=models.RecodeText(models.RECODE_NODATA)
return
}
beego.Info("reg success,id=",id)
resp["errno"]=models.RECODE_OK
resp["errmsg"]=models.RecodeText(models.RECODE_OK)
c.SetSession("name",user.Name)
}
func (c *UserController) RetData(resp map[string]interface{}) {
c.Data["json"] =resp
c.ServeJSON()
}
controllers>Session.go 登录
package controllers
import (
"encoding/json"
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
"lovehome/models"
)
type SessionController struct {
beego.Controller
}
func (c *SessionController) Get() {
c.Data["Website"] = "beego.me"
c.Data["Email"] = "astaxie@gmail.com"
c.TplName = "index.tpl"
}
//TODO 获取Session
func (c *SessionController) GetSessionData() {
beego.Info("connect success")
resp :=make(map[string]interface{})
defer c.RetData(resp)
user := models.User{}
//user.Name="浩秦"
resp["errno"] = 4001
resp["errmsg"] = "数据获取失败"
name := c.GetSession("name")
if name!=nil {
user.Name = name.(string)
resp["errno"] = 0
resp["mrrmsg"] = "ok"
resp["data"] = user
}
}
//TODO 删除对应的Session
func (c *SessionController) DeleteSessionData() {
resp := make(map[string]interface{})
defer c.RetData(resp)
c.DelSession("name")
resp["errno"]=0
resp["errmsg"]="ok"
}
// TODO 登录
func (c *SessionController) Login() {
resp := make(map[string]interface{})
defer c.RetData(resp)
//得到用户信息获取前端传递过来的json数据
json.Unmarshal(c.Ctx.Input.RequestBody,&resp)
beego.Info(&resp)
//判断是否合法
if resp["mobile"] == nil || resp["password"] ==nil{
resp["errno"]=models.RECODE_DATAERR
resp["errmsg"]=models.RecodeText(models.RECODE_DATAERR)
return
}
//与数据库匹配账号密码是否正确
o := orm.NewOrm()
user := models.User{Name:resp["mobile"].(string)}
moble := resp["mobile"].(string)
qs := o.QueryTable("user")
err := qs.Filter("mobile",moble).One(&user)
if err !=nil {
resp["errno"]=models.RECODE_DATAERR
resp["errmsg"]=models.RecodeText(models.RECODE_DATAERR)
beego.Info("2222name=",resp["mobile"],"========password====",resp["password"])
return
}
if user.Password_hash != resp["password"] {
resp["errno"]=models.RECODE_DATAERR
resp["errmsg"]=models.RecodeText(models.RECODE_DATAERR)
beego.Info("3333name=",resp["mobile"],"========password====",resp["password"])
return
}
//添加Session
c.SetSession("name",resp["mobile"])
c.SetSession("mobile",resp["mobile"])
c.SetSession("user_id",user.Id)
//返回json数据给前端
resp["errno"]=models.RECODE_OK
resp["errmsg"]=models.RecodeText(models.RECODE_OK)
}
func (c *SessionController) RetData(resp map[string]interface{}) {
c.Data["json"] =resp
c.ServeJSON()
}
controllers>area.go
package controllers
import (
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
"lovehome/models"
)
type LAreaControllers struct {
beego.Controller
}
func (c *LAreaControllers) Get() {
c.Data["Website"] = "beego.me"
c.Data["Email"] = "astaxie@gmail.com"
c.TplName = "index.tpl"
}
func (c *LAreaControllers) GetArea() {
beego.Info("connect success")
resp :=make(map[string]interface{})
resp["errno"]=0
resp["errmsg"]="ok"
defer c.RetData(resp)
//TODO 从MySQL里面读取数据
var areas []models.Area
o := orm.NewOrm()
num,err := o.QueryTable("area").All(&areas)
if err != nil {
resp["errno"]=4001
resp["errmsg"]="数据库查询失败"
return
}
if num == 0 {
resp["errno"]=4002
resp["errmsg"]="没有查到数据"
}
//TODO 打包成json返回给前端
resp["data"]=areas
beego.Info("query data sucess,resp=",resp,"num=",num)
}
func (c *LAreaControllers) RetData(resp map[string]interface{}) {
c.Data["json"] =resp
c.ServeJSON()
}
main.go beego前后端分离静态页面承载有点费劲,不过也好只是比gin多几句代码而已
package main
import (
_ "lovehome/routers"
_ "lovehome/models"
"github.com/astaxie/beego"
"github.com/astaxie/beego/context"
"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){
orpath := ctx.Request.URL.Path
beego.Info("request url:",orpath)
//如果请求url包含api字段,说明指令应该取消静态资源重定向
if strings.Index(orpath,"api") >= 0{
return
}
http.ServeFile(ctx.ResponseWriter,ctx.Request,"static/html/"+ctx.Request.URL.Path)
}