context.go 903 B

12345678910111213141516171819202122232425262728293031323334
  1. package service
  2. import (
  3. "context"
  4. "dashoo.cn/micro/app/model"
  5. "github.com/gogf/gf/net/ghttp"
  6. )
  7. // Context 上下文管理服务
  8. var Context = new(contextService)
  9. type contextService struct{}
  10. // Init 初始化上下文对象指针到上下文对象中,以便后续的请求流程中可以修改。
  11. func (s *contextService) Init(r *ghttp.Request, customCtx *model.Context) {
  12. r.SetCtxVar(model.CtxKey, customCtx)
  13. }
  14. // Get 获得上下文变量,如果没有设置,那么返回nil
  15. func (s *contextService) Get(ctx context.Context) *model.Context {
  16. value := ctx.Value(model.CtxKey)
  17. if value == nil {
  18. return nil
  19. }
  20. if localCtx, ok := value.(*model.Context); ok {
  21. return localCtx
  22. }
  23. return nil
  24. }
  25. // SetUser 将上下文信息设置到上下文请求中,注意是完整覆盖
  26. func (s *contextService) SetUser(ctx context.Context, ctxUser *model.CtxUser) {
  27. s.Get(ctx).User = ctxUser
  28. }