Files
zmkgC/internal/app/system/logic/context/context.go

71 lines
1.7 KiB
Go
Raw Normal View History

2025-07-07 20:11:59 +08:00
/*
* @desc:context-service
* @company:云南奇讯科技有限公司
* @Author: yixiaohu<yxh669@qq.com>
* @Date: 2022/9/23 14:51
*/
package context
import (
"context"
"github.com/gogf/gf/v2/net/ghttp"
"github.com/tiger1103/gfast/v3/internal/app/system/consts"
"github.com/tiger1103/gfast/v3/internal/app/system/model"
"github.com/tiger1103/gfast/v3/internal/app/system/service"
)
func init() {
service.RegisterContext(New())
}
type sContext struct{}
func New() *sContext {
return &sContext{}
}
// Init 初始化上下文对象指针到上下文对象中,以便后续的请求流程中可以修改。
func (s *sContext) Init(r *ghttp.Request, customCtx *model.Context) {
r.SetCtxVar(consts.CtxKey, customCtx)
}
// Get 获得上下文变量如果没有设置那么返回nil
func (s *sContext) Get(ctx context.Context) *model.Context {
value := ctx.Value(consts.CtxKey)
if value == nil {
return nil
}
if localCtx, ok := value.(*model.Context); ok {
return localCtx
}
return nil
}
// SetUser 将上下文信息设置到上下文请求中,注意是完整覆盖
func (s *sContext) SetUser(ctx context.Context, ctxUser *model.ContextUser) {
s.Get(ctx).User = ctxUser
}
// GetLoginUser 获取当前登陆用户信息
func (s *sContext) GetLoginUser(ctx context.Context) *model.ContextUser {
context := s.Get(ctx)
if context == nil {
return nil
}
return context.User
//user := model.ContextUser{}
//user.LoginUserRes = &model.LoginUserRes{}
//user.Id = 1
//return &user
}
// GetUserId 获取当前登录用户id
func (s *sContext) GetUserId(ctx context.Context) uint64 {
user := s.GetLoginUser(ctx)
if user != nil {
return user.Id
}
return 0
}