base_context.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package base
  2. import (
  3. "github.com/gogf/gf/v2/net/ghttp"
  4. "golang.org/x/net/context"
  5. "nodeMonitor/internal/consts"
  6. "nodeMonitor/internal/model"
  7. )
  8. type IContext interface {
  9. Init(r *ghttp.Request, customCtx *model.Context)
  10. Get(ctx context.Context) *model.Context
  11. SetUser(ctx context.Context, ctxUser *model.ContextUser)
  12. GetLoginUser(ctx context.Context) *model.ContextUser
  13. }
  14. // Context 上下文管理服务
  15. var contextService = contextImpl{}
  16. type contextImpl struct{}
  17. func Context() IContext {
  18. return IContext(&contextService)
  19. }
  20. // Init 初始化上下文对象指针到上下文对象中,以便后续的请求流程中可以修改。
  21. func (s *contextImpl) Init(r *ghttp.Request, customCtx *model.Context) {
  22. r.SetCtxVar(consts.CtxKey, customCtx)
  23. }
  24. // Get 获得上下文变量,如果没有设置,那么返回nil
  25. func (s *contextImpl) Get(ctx context.Context) *model.Context {
  26. value := ctx.Value(consts.CtxKey)
  27. if value == nil {
  28. return nil
  29. }
  30. if localCtx, ok := value.(*model.Context); ok {
  31. return localCtx
  32. }
  33. return nil
  34. }
  35. // SetUser 将上下文信息设置到上下文请求中,注意是完整覆盖
  36. func (s *contextImpl) SetUser(ctx context.Context, ctxUser *model.ContextUser) {
  37. s.Get(ctx).User = ctxUser
  38. }
  39. // GetLoginUser 获取当前登陆用户信息
  40. func (s *contextImpl) GetLoginUser(ctx context.Context) *model.ContextUser {
  41. context := s.Get(ctx)
  42. if context == nil {
  43. return nil
  44. }
  45. return context.User
  46. }