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) }