gplus.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. package gplus
  2. import (
  3. "context"
  4. "github.com/gogf/gf/v2/net/ghttp"
  5. iContext "gxt-api-frame/app/context"
  6. "gxt-api-frame/app/errors"
  7. "gxt-api-frame/app/schema"
  8. "gxt-api-frame/library/logger"
  9. "gxt-api-frame/library/utils"
  10. "net/http"
  11. "strings"
  12. )
  13. // 定义上下文中的键
  14. const (
  15. prefix = "gao-xin-tong"
  16. // UserIDKey 存储上下文中的键(用户ID)
  17. UserIDKey = prefix + "/user-id"
  18. // UserTypeKey 存储上下文中的键(用户类型)
  19. UserTypeKey = prefix + "/user-type"
  20. // TraceIDKey 存储上下文中的键(跟踪ID)
  21. TraceIDKey = prefix + "/trace-id"
  22. // ResBodyKey 存储上下文中的键(响应Body数据)
  23. ResBodyKey = prefix + "/res-body"
  24. )
  25. // ParseJson 解析请求参数Json
  26. func ParseJson(r *ghttp.Request, out interface{}) error {
  27. if err := r.Parse(out); err != nil {
  28. m := "解析请求参数发生错误"
  29. if utils.GetConfig("common.run_mode").String() == "debug" {
  30. m += "[" + err.Error() + "]"
  31. }
  32. return errors.Wrap400Response(err, m)
  33. }
  34. return nil
  35. }
  36. // GetPageIndex 获取当前页
  37. func GetPageIndex(r *ghttp.Request) int {
  38. defaultVal := 1
  39. if v := r.GetQuery("current").Int(); v > 0 {
  40. return v
  41. }
  42. return defaultVal
  43. }
  44. // GetPageSize 获取分页的页大小(最大50)
  45. func GetPageSize(r *ghttp.Request) int {
  46. defaultVal := 10
  47. if v := r.GetQuery("pageSize").Int(); v > 0 {
  48. if v > 50 {
  49. v = 50
  50. }
  51. return v
  52. }
  53. return defaultVal
  54. }
  55. // ResPage 分页响应
  56. func ResPage(r *ghttp.Request, v interface{}, pr *schema.PaginationResult) {
  57. result := schema.HTTPList{
  58. List: v,
  59. Pagination: &schema.HTTPPagination{
  60. Current: GetPageIndex(r),
  61. PageSize: GetPageSize(r),
  62. },
  63. }
  64. if pr != nil {
  65. result.Pagination.Total = pr.Total
  66. }
  67. ResSuccess(r, result)
  68. }
  69. // ResSuccess 响应成功
  70. func ResSuccess(c *ghttp.Request, v interface{}) {
  71. ResJSON(c, http.StatusOK, v)
  72. }
  73. // ResOK 响应OK
  74. func ResOK(c *ghttp.Request) {
  75. ResSuccess(c, schema.HTTPStatus{Status: "OK"})
  76. }
  77. // ResList 响应列表数据
  78. func ResList(c *ghttp.Request, v interface{}) {
  79. ResSuccess(c, schema.HTTPList{List: v})
  80. }
  81. // ResJSON 响应JSON结果
  82. func ResJSON(r *ghttp.Request, code int, v interface{}) {
  83. errors.JsonExit(r, code, v)
  84. }
  85. // ResError 响应错误
  86. func ResError(r *ghttp.Request, err error, status ...int) {
  87. var res *errors.ResponseError
  88. if err != nil {
  89. if e, ok := err.(*errors.ResponseError); ok {
  90. res = e
  91. } else {
  92. res = errors.UnWrapResponse(errors.Wrap500Response(err))
  93. }
  94. } else {
  95. res = errors.UnWrapResponse(errors.ErrInternalServer)
  96. }
  97. if len(status) > 0 {
  98. res.StatusCode = status[0]
  99. }
  100. if err := res.ERR; err != nil {
  101. if res.StatusCode >= 500 {
  102. logger.Errorf(NewContext(r), "%s", err)
  103. }
  104. }
  105. eitem := schema.HTTPErrorItem{
  106. Code: res.Code,
  107. Message: res.Message,
  108. TraceId: GetTraceID(r),
  109. }
  110. ResJSON(r, res.StatusCode, schema.HTTPError{Error: eitem})
  111. }
  112. // SetUserId 上下文中设置用户Id
  113. func SetUserId(r *ghttp.Request, userId string) {
  114. r.SetCtxVar(UserIDKey, userId)
  115. }
  116. // GetUserId 获取上下文中的用户Id
  117. func GetUserId(r *ghttp.Request) string {
  118. return r.GetCtxVar(UserIDKey).String()
  119. }
  120. // GetToken 获取token
  121. func GetToken(r *ghttp.Request) string {
  122. var token string
  123. auth := r.GetHeader("Authorization")
  124. prefix := "Bearer "
  125. if auth != "" && strings.HasPrefix(auth, prefix) {
  126. token = auth[len(prefix):]
  127. }
  128. return token
  129. }
  130. // NewContext 封装上下文入口
  131. func NewContext(r *ghttp.Request) context.Context {
  132. parent := context.Background()
  133. traceId := GetTraceID(r)
  134. if traceId == "" {
  135. traceId = utils.NewTraceID()
  136. }
  137. parent = iContext.NewTraceID(parent, traceId)
  138. parent = logger.NewTraceIDContext(parent, traceId)
  139. if v := GetUserID(r); v != "" {
  140. parent = iContext.NewUserID(parent, v)
  141. parent = logger.NewUserIDContext(parent, v)
  142. }
  143. return parent
  144. }
  145. // GetTraceID 获取追踪ID
  146. func GetTraceID(c *ghttp.Request) string {
  147. return c.GetCtxVar(TraceIDKey).String()
  148. }
  149. // GetUserID 获取用户ID
  150. func GetUserID(c *ghttp.Request) string {
  151. return c.GetCtxVar(UserIDKey).String()
  152. }
  153. // GetUserType 获取用户类型
  154. func GetUserType(c *ghttp.Request) string {
  155. return c.GetCtxVar(UserTypeKey).String()
  156. }