Files
jx-callback/business/jxutils/jxcontext/jxcontext.go
2018-10-29 14:54:40 +08:00

109 lines
2.0 KiB
Go

package jxcontext
import (
"net/http"
"sync"
"git.rosy.net.cn/jx-callback/business/jxcallback/auth"
"git.rosy.net.cn/jx-callback/business/jxutils/tasksch"
)
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, _, _ = New(nil, "jxadmin", nil, nil)
}
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)
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) 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]
}