context.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. * @desc:context-service
  3. * @company:云南奇讯科技有限公司
  4. * @Author: yixiaohu
  5. * @Date: 2022/3/16 14:46
  6. */
  7. package service
  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. )
  14. type IContext interface {
  15. Init(r *ghttp.Request, customCtx *model.Context)
  16. Get(ctx context.Context) *model.Context
  17. SetUser(ctx context.Context, ctxUser *model.ContextUser)
  18. GetLoginUser(ctx context.Context) *model.ContextUser
  19. GetUserId(ctx context.Context) uint64
  20. }
  21. // Context 上下文管理服务
  22. var contextImpl = contextServiceImpl{}
  23. type contextServiceImpl struct{}
  24. func Context() IContext {
  25. return IContext(&contextImpl)
  26. }
  27. // Init 初始化上下文对象指针到上下文对象中,以便后续的请求流程中可以修改。
  28. func (s *contextServiceImpl) Init(r *ghttp.Request, customCtx *model.Context) {
  29. r.SetCtxVar(consts.CtxKey, customCtx)
  30. }
  31. // Get 获得上下文变量,如果没有设置,那么返回nil
  32. func (s *contextServiceImpl) Get(ctx context.Context) *model.Context {
  33. value := ctx.Value(consts.CtxKey)
  34. if value == nil {
  35. return nil
  36. }
  37. if localCtx, ok := value.(*model.Context); ok {
  38. return localCtx
  39. }
  40. return nil
  41. }
  42. // SetUser 将上下文信息设置到上下文请求中,注意是完整覆盖
  43. func (s *contextServiceImpl) SetUser(ctx context.Context, ctxUser *model.ContextUser) {
  44. s.Get(ctx).User = ctxUser
  45. }
  46. // GetLoginUser 获取当前登陆用户信息
  47. func (s *contextServiceImpl) GetLoginUser(ctx context.Context) *model.ContextUser {
  48. context := s.Get(ctx)
  49. if context == nil {
  50. return nil
  51. }
  52. return context.User
  53. }
  54. // GetUserId 获取当前登录用户id
  55. func (s *contextServiceImpl) GetUserId(ctx context.Context) uint64 {
  56. user := s.GetLoginUser(ctx)
  57. if user != nil {
  58. return user.Id
  59. }
  60. return 0
  61. }