context.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. * @desc:context-service
  3. * @company:云南奇讯科技有限公司
  4. * @Author: yixiaohu<yxh669@qq.com>
  5. * @Date: 2022/9/23 14:51
  6. */
  7. package context
  8. import (
  9. "context"
  10. "github.com/gogf/gf/v2/net/ghttp"
  11. "github.com/tiger1103/gfast/v3/internal/app/system/consts"
  12. "github.com/tiger1103/gfast/v3/internal/app/system/model"
  13. "github.com/tiger1103/gfast/v3/internal/app/system/service"
  14. )
  15. func init() {
  16. service.RegisterContext(New())
  17. }
  18. type sContext struct{}
  19. func New() *sContext {
  20. return &sContext{}
  21. }
  22. // Init 初始化上下文对象指针到上下文对象中,以便后续的请求流程中可以修改。
  23. func (s *sContext) Init(r *ghttp.Request, customCtx *model.Context) {
  24. r.SetCtxVar(consts.CtxKey, customCtx)
  25. }
  26. // Get 获得上下文变量,如果没有设置,那么返回nil
  27. func (s *sContext) Get(ctx context.Context) *model.Context {
  28. value := ctx.Value(consts.CtxKey)
  29. if value == nil {
  30. return nil
  31. }
  32. if localCtx, ok := value.(*model.Context); ok {
  33. return localCtx
  34. }
  35. return nil
  36. }
  37. // SetUser 将上下文信息设置到上下文请求中,注意是完整覆盖
  38. func (s *sContext) SetUser(ctx context.Context, ctxUser *model.ContextUser) {
  39. s.Get(ctx).User = ctxUser
  40. }
  41. // GetLoginUser 获取当前登陆用户信息
  42. func (s *sContext) GetLoginUser(ctx context.Context) *model.ContextUser {
  43. context := s.Get(ctx)
  44. if context == nil {
  45. return nil
  46. }
  47. return context.User
  48. }
  49. // GetUserId 获取当前登录用户id
  50. func (s *sContext) GetUserId(ctx context.Context) uint64 {
  51. user := s.GetLoginUser(ctx)
  52. if user != nil {
  53. return user.Id
  54. }
  55. return 0
  56. }