context.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package service
  2. import (
  3. "context"
  4. "github.com/gogf/gf/os/glog"
  5. "dashoo.cn/opms_libary/micro_srv"
  6. "dashoo.cn/opms_libary/request"
  7. )
  8. // ContextService 上下文管理服务
  9. type ContextService struct {
  10. Tenant string `json:"tenant"`
  11. Table string `json:"table"`
  12. Ctx context.Context `json:"ctx"`
  13. CxtUser *request.UserInfo `json:"cxtUser"`
  14. }
  15. // Init 初始化上下文对象指针到上下文对象中,以便后续的请求流程中可以修改。
  16. func (c *ContextService) Init(ctx context.Context) (*ContextService, error) {
  17. cs := ctx.Value("contextService")
  18. if cs != nil {
  19. return cs.(*ContextService), nil
  20. }
  21. c = new(ContextService)
  22. c.Ctx = ctx
  23. // 获取租户码
  24. tenant, err := micro_srv.GetTenant(ctx)
  25. if err != nil {
  26. return nil, err
  27. }
  28. reqMethod, _ := micro_srv.GetReqMethod(ctx)
  29. glog.Info("Received " + reqMethod + " request @ " + tenant)
  30. c.Tenant = tenant
  31. c.CxtUser = nil
  32. if !micro_srv.IsAuthExclude(ctx) {
  33. userInfo, err := micro_srv.GetUserInfo(ctx)
  34. if err != nil {
  35. return nil, err
  36. }
  37. c.CxtUser = &userInfo
  38. }
  39. c.Ctx = context.WithValue(ctx, "contextService", c)
  40. return c, nil
  41. }
  42. func (c *ContextService) GetCxtUserId() int {
  43. if c.CxtUser == nil {
  44. return -1
  45. }
  46. return c.CxtUser.Id
  47. }
  48. func (c *ContextService) GetCxtUserUuid() string {
  49. if c.CxtUser == nil {
  50. return "-1"
  51. }
  52. return c.CxtUser.Uuid
  53. }
  54. func (c *ContextService) GetCxtUserName() string {
  55. if c.CxtUser == nil {
  56. return "-1"
  57. }
  58. return c.CxtUser.NickName
  59. }
  60. func (c *ContextService) GetCxtUserDeptId() int {
  61. if c.CxtUser == nil {
  62. return -1
  63. }
  64. return c.CxtUser.DeptId
  65. }
  66. func (c *ContextService) GetCxtUserRoles() []string {
  67. if c.CxtUser == nil {
  68. return []string{}
  69. }
  70. return c.CxtUser.Roles
  71. }
  72. func (c *ContextService) GetCxtUserPosts() []string {
  73. if c.CxtUser == nil {
  74. return []string{}
  75. }
  76. return c.CxtUser.Posts
  77. }
  78. func (c *ContextService) GetCxtUserGroups() []string {
  79. if c.CxtUser == nil {
  80. return []string{}
  81. }
  82. return c.CxtUser.Groups
  83. }