112 lines
2.2 KiB
Go
112 lines
2.2 KiB
Go
package controllers
|
|
|
|
import (
|
|
"errors"
|
|
"github.com/astaxie/beego"
|
|
"github.com/satori/go.uuid"
|
|
"liteblog/models"
|
|
"liteblog/syserrors"
|
|
)
|
|
|
|
const SESSION_USER_KEY = "SESSION_USER_KEY"
|
|
|
|
type NestPreparer interface {
|
|
NestPrepare()
|
|
}
|
|
|
|
type BaseController struct {
|
|
beego.Controller
|
|
IsLogin bool // 标识 用户是否登陆
|
|
User models.User // 登陆的用户
|
|
}
|
|
|
|
func (ctx *BaseController) Prepare() {
|
|
// 将页面路径保存到path变量中
|
|
ctx.Data["Path"] = ctx.Ctx.Request.RequestURI
|
|
// 记录登陆的状态
|
|
ctx.IsLogin = false
|
|
tu := ctx.GetSession(SESSION_USER_KEY)
|
|
if tu != nil {
|
|
if u, ok := tu.(models.User); ok {
|
|
ctx.User = u
|
|
ctx.Data["User"] = u
|
|
ctx.IsLogin = true
|
|
}
|
|
}
|
|
ctx.Data["IsLogin"] = ctx.IsLogin
|
|
|
|
if app, ok := ctx.AppController.(NestPreparer); ok {
|
|
app.NestPrepare()
|
|
}
|
|
}
|
|
|
|
func (ctx *BaseController) MustLogin() {
|
|
if !ctx.IsLogin {
|
|
ctx.Abort500(syserrors.NoUserError{})
|
|
}
|
|
}
|
|
|
|
func (ctx *BaseController) GetMustString(key string, msg string) string {
|
|
KeyString := ctx.GetString(key, "")
|
|
if len(KeyString) == 0 {
|
|
ctx.Abort500(errors.New(msg))
|
|
}
|
|
return KeyString
|
|
}
|
|
|
|
func (ctx *BaseController) Abort500(err error) {
|
|
ctx.Data["Error"] = err
|
|
ctx.Abort("500")
|
|
}
|
|
|
|
type H map[string]interface{}
|
|
|
|
type ResultJsonValue struct {
|
|
Code int `json:"code"`
|
|
Msg string `json:"msg"`
|
|
Action string `json:"action,omitempty"`
|
|
Count int `json:"count,omitempty"`
|
|
Data interface{} `json:"data,omitempty"`
|
|
}
|
|
|
|
func (ctx *BaseController) JSONOk(msg string, actions ...string) {
|
|
var action string
|
|
if len(actions) > 0 {
|
|
action = actions[0]
|
|
}
|
|
ctx.Data["json"] = &ResultJsonValue{
|
|
Code: 0,
|
|
Msg: msg,
|
|
Action: action,
|
|
}
|
|
ctx.ServeJSON()
|
|
}
|
|
|
|
func (ctx *BaseController) JSONOkH(msg string, maps H) {
|
|
if maps == nil {
|
|
maps = H{}
|
|
}
|
|
maps["code"] = 0
|
|
maps["msg"] = msg
|
|
ctx.Data["json"] = maps
|
|
ctx.ServeJSON()
|
|
}
|
|
|
|
func (ctx *BaseController) JSONOkData(count int, data interface{}) {
|
|
ctx.Data["json"] = &ResultJsonValue{
|
|
Code: 0,
|
|
Count: count,
|
|
Msg: "成功!",
|
|
Data: data,
|
|
}
|
|
ctx.ServeJSON()
|
|
}
|
|
|
|
func (ctx *BaseController) UUID() string {
|
|
u, err := uuid.NewV4()
|
|
if err != nil {
|
|
ctx.Abort500(syserrors.NewError("系统错误", err))
|
|
}
|
|
|
|
return u.String()
|
|
} |