package jxcontext import ( "net/http" "sync" "git.rosy.net.cn/jx-callback/business/jxcallback/auth" "git.rosy.net.cn/jx-callback/business/jxutils/tasksch" "git.rosy.net.cn/jx-callback/business/model" "git.rosy.net.cn/jx-callback/globals" "github.com/astaxie/beego" ) type Context struct { rootTask tasksch.ITask token string userInfo *auth.LoginInfo w http.ResponseWriter r *http.Request mapData map[interface{}]interface{} locker sync.RWMutex } const ( MaxUserNameLen = 30 ) var ( AdminCtx *Context ) func init() { AdminCtx = NewWithUserName(nil, "jxadmin", nil, nil) } func NewWithUserName(rootTask tasksch.ITask, userName string, w http.ResponseWriter, r *http.Request) (ctx *Context) { ctx = &Context{ rootTask: rootTask, token: userName, w: w, r: r, mapData: make(map[interface{}]interface{}), } return ctx } func New(rootTask tasksch.ITask, token string, w http.ResponseWriter, r *http.Request) (ctx *Context, errCode string, err error) { ctx = &Context{ rootTask: rootTask, token: token, w: w, r: r, mapData: make(map[interface{}]interface{}), } ctx.userInfo, err = auth.GetUserInfo(token) if err != nil && beego.BConfig.RunMode == "prod" { globals.SugarLogger.Debugf("token is invalid, token:%s", token) return nil, model.ErrCodeTokenIsInvalid, err } return ctx, "", nil } func (ctx *Context) GetUserName() string { userName := ctx.token if ctx.userInfo != nil { userName = ctx.userInfo.ID } if len(userName) > MaxUserNameLen { userName = userName[:MaxUserNameLen] } return userName } func (ctx *Context) GetLoginType() string { if ctx.userInfo != nil { return ctx.userInfo.LoginType } return "" } func (ctx *Context) GetUserID() string { return ctx.token } func (ctx *Context) GetRootTask() tasksch.ITask { ctx.locker.RLock() defer ctx.locker.RUnlock() return ctx.rootTask } func (ctx *Context) SetTaskOrAddChild(task tasksch.ITask, parentTask tasksch.ITask) bool { if parentTask != nil { parentTask.AddChild(task) } else { parentTask = task } ctx.locker.RLock() if ctx.rootTask == nil { ctx.locker.RUnlock() ctx.locker.Lock() if ctx.rootTask == nil { ctx.rootTask = parentTask } ctx.locker.Unlock() return true } ctx.locker.RUnlock() return false } func (ctx *Context) GetResponseWriter() http.ResponseWriter { return ctx.w } func (ctx *Context) GetRequest() *http.Request { return ctx.r } func (ctx *Context) SetValue(key, value interface{}) { ctx.locker.Lock() defer ctx.locker.Unlock() ctx.mapData[key] = value } func (ctx *Context) GetValue(key interface{}) interface{} { ctx.locker.RLock() defer ctx.locker.RUnlock() return ctx.mapData[key] }