controller.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. package api
  2. import (
  3. "box-cost/log"
  4. "crypto/md5"
  5. "encoding/json"
  6. "fmt"
  7. "net/http"
  8. "runtime"
  9. "strconv"
  10. "strings"
  11. jwt "github.com/appleboy/gin-jwt/v2"
  12. "github.com/gin-gonic/gin"
  13. )
  14. // Handler 包装http处理函数
  15. type Handler func(c *gin.Context, apictx *ApiSession) (interface{}, error)
  16. // JWTHander JWT授权的http处理函数
  17. type JWTHander func(c *gin.Context, apictx *ApiSession) (interface{}, error)
  18. // ResultWrapper 统一返回结果处理
  19. func ResultWrapper(handle Handler, svc *Service) gin.HandlerFunc {
  20. return func(c *gin.Context) {
  21. defer func() {
  22. if r := recover(); r != nil {
  23. fmt.Println("recover success.")
  24. fmt.Println(r)
  25. buf := make([]byte, 1<<16)
  26. runtime.Stack(buf, true)
  27. fmt.Println("buf", string(buf))
  28. c.JSON(http.StatusOK, NewFailResultWithData("系统异常", r))
  29. }
  30. }()
  31. data, err := handle(c, &ApiSession{Svc: svc, User: nil})
  32. if err != nil {
  33. httpErr, ok := err.(HTTPError)
  34. if ok {
  35. c.JSON(http.StatusOK, NewFailResultWithCode(httpErr.Error(), httpErr.Code))
  36. return
  37. }
  38. c.JSON(http.StatusOK, NewFailResult(err.Error()))
  39. return
  40. }
  41. if data != nil {
  42. c.JSON(http.StatusOK, NewOkResult(data))
  43. }
  44. }
  45. }
  46. // ResultJWTWrapper JWT授权处理handler
  47. func ResultJWTWrapper(handle JWTHander, svc *Service) gin.HandlerFunc {
  48. return func(c *gin.Context) {
  49. defer func() {
  50. if r := recover(); r != nil {
  51. fmt.Println("recover success.")
  52. fmt.Println(r)
  53. buf := make([]byte, 1<<16)
  54. runtime.Stack(buf, true)
  55. fmt.Println("buf", string(buf))
  56. c.JSON(http.StatusOK, NewFailResultWithData("系统异常", r))
  57. }
  58. }()
  59. claims := jwt.ExtractClaims(c)
  60. var usr *JWTUser
  61. if claims["id"] != nil {
  62. id := claims["id"].(string)
  63. name := claims["phone"].(string)
  64. role := claims["role"].(string)
  65. parent := claims["parent"].(string)
  66. state := int32(claims["state"].(float64))
  67. usr = &JWTUser{ID: id, Phone: name, Parent: parent, Role: role, State: state}
  68. }
  69. var apis = &ApiSession{
  70. Svc: svc,
  71. User: usr,
  72. }
  73. data, err := handle(c, apis)
  74. if err != nil {
  75. fmt.Println(err)
  76. httpErr, ok := err.(HTTPError)
  77. if ok {
  78. c.JSON(http.StatusOK, NewFailResultWithCode(httpErr.Error(), httpErr.Code))
  79. return
  80. }
  81. c.JSON(http.StatusOK, NewFailResult(err.Error()))
  82. return
  83. }
  84. if data != nil {
  85. c.JSON(http.StatusOK, NewOkResult(data))
  86. }
  87. }
  88. }
  89. // ResultJWTTestWrapper test 默认一个测试用户 JWT授权处理handler
  90. func ResultJWTTestWrapper(handle JWTHander, svc *Service) gin.HandlerFunc {
  91. return func(c *gin.Context) {
  92. defer func() {
  93. if r := recover(); r != nil {
  94. fmt.Println("recover success.")
  95. fmt.Println(r)
  96. buf := make([]byte, 1<<16)
  97. runtime.Stack(buf, true)
  98. fmt.Println("buf", string(buf))
  99. c.JSON(http.StatusOK, NewFailResultWithData("error", r))
  100. }
  101. }()
  102. var usr *JWTUser = &JWTUser{ID: svc.DebugUserId, Phone: svc.DebugUserPhone, Parent: svc.DebugUserId, Role: svc.DebugUserRole}
  103. data, err := handle(c, &ApiSession{Svc: svc, User: usr})
  104. if err != nil {
  105. fmt.Println(err)
  106. httpErr, ok := err.(HTTPError)
  107. if ok {
  108. c.JSON(http.StatusOK, NewFailResultWithCode(httpErr.Error(), httpErr.Code))
  109. return
  110. }
  111. c.JSON(http.StatusOK, NewFailResult(err.Error()))
  112. return
  113. }
  114. c.JSON(http.StatusOK, NewOkResult(data))
  115. }
  116. }
  117. // ResultSuc 成功
  118. func ResultSuc(c *gin.Context, data interface{}) {
  119. c.JSON(http.StatusOK, NewOkResult(data))
  120. }
  121. // ResultFail 失败
  122. func ResultFail(c *gin.Context, msg string) {
  123. c.JSON(http.StatusOK, NewFailResult(msg))
  124. }
  125. // ResultFail401 失败2
  126. func ResultFail401(c *gin.Context, msg string, data interface{}) {
  127. c.JSON(http.StatusOK, &HTTPResult{ErrorNo: 401, Result: data, ErrorDesc: msg})
  128. }
  129. // UtilMd5 结算md5的值
  130. func UtilMd5(s string) string {
  131. data := []byte(s)
  132. has := md5.Sum(data)
  133. return fmt.Sprintf("%x", has)
  134. }
  135. // UtilQueryPageSize 分页数据
  136. func UtilQueryPageSize(c *gin.Context) (page int64, size int64, query map[string]interface{}) {
  137. p := c.Query("page")
  138. s := c.Query("size")
  139. q := c.Query("query")
  140. var _page = 1
  141. if len(p) > 0 {
  142. _page, _ = strconv.Atoi(p)
  143. }
  144. page = int64(_page)
  145. var _size = 10
  146. if len(s) > 0 {
  147. _size, _ = strconv.Atoi(s)
  148. }
  149. size = int64(_size)
  150. if len(q) > 0 {
  151. json.Unmarshal([]byte(q), &query)
  152. } else {
  153. query = map[string]interface{}{}
  154. }
  155. return
  156. }
  157. func UtilQueryPageSize2(c *gin.Context) (page int64, size int64, query map[string]interface{}, fields []string) {
  158. p := c.Query("page")
  159. s := c.Query("size")
  160. q := c.Query("query")
  161. f := c.Query("fields")
  162. var _page = 1
  163. if len(p) > 0 {
  164. _page, _ = strconv.Atoi(p)
  165. }
  166. page = int64(_page)
  167. var _size = 10
  168. if len(s) > 0 {
  169. _size, _ = strconv.Atoi(s)
  170. }
  171. size = int64(_size)
  172. if len(q) > 0 {
  173. json.Unmarshal([]byte(q), &query)
  174. } else {
  175. query = map[string]interface{}{}
  176. }
  177. if len(f) > 0 {
  178. fields = strings.Split(f, ",")
  179. } else {
  180. fields = []string{}
  181. }
  182. return
  183. }
  184. // HTTPResult 客户端统一返回结构体
  185. type HTTPResult struct {
  186. ErrorNo int32 `json:"errorNo"`
  187. Result interface{} `json:"result"`
  188. ErrorDesc string `json:"errorDesc"`
  189. }
  190. func (err HTTPResult) Error() string {
  191. return err.ErrorDesc
  192. }
  193. // HTTPError 统一错误处理
  194. type HTTPError struct {
  195. Code int32 `json:"code"`
  196. Message string `json:"message"`
  197. }
  198. func (err HTTPError) Error() string {
  199. return err.Message
  200. }
  201. // NewOkResult 创建正确结果
  202. func NewOkResult(obj interface{}) *HTTPResult {
  203. return &HTTPResult{ErrorNo: 200, Result: obj}
  204. }
  205. // NewFailResult 创建错误结构
  206. func NewFailResult(desc string) *HTTPResult {
  207. return &HTTPResult{ErrorNo: 500, Result: nil, ErrorDesc: desc}
  208. }
  209. // NewFailResultWithData 创建错误返回结果
  210. func NewFailResultWithData(desc string, data interface{}) *HTTPResult {
  211. return &HTTPResult{ErrorNo: 500, Result: data, ErrorDesc: desc}
  212. }
  213. // NewFailResultWithCode 创建错误结构
  214. func NewFailResultWithCode(desc string, code int32) *HTTPResult {
  215. return &HTTPResult{ErrorNo: code, Result: nil, ErrorDesc: desc}
  216. }
  217. // NewError NewError
  218. func NewError(desc string) HTTPError {
  219. return HTTPError{Code: 500, Message: desc}
  220. }
  221. func NewLogError(desc string) HTTPError {
  222. pc, file, line, _ := runtime.Caller(1)
  223. log.Errorf("%s:%d=>%s %v", file, line, runtime.FuncForPC(pc).Name(), desc)
  224. return HTTPError{Code: 500, Message: desc}
  225. }
  226. func NewLogWithError(err error) HTTPError {
  227. pc, file, line, _ := runtime.Caller(1)
  228. log.Errorf("%s:%d=>%s %s", file, line, runtime.FuncForPC(pc).Name(), err.Error())
  229. return HTTPError{Code: 500, Message: err.Error()}
  230. }
  231. // NewErrorWithCode NewErrorWithCode
  232. func NewErrorWithCode(desc string, code int32) HTTPError {
  233. return HTTPError{Code: code, Message: desc}
  234. }
  235. // JWTUser jwt登录用户
  236. type JWTUser struct {
  237. ID string `json:"id"`
  238. Parent string `json:"parent"`
  239. Phone string `json:"phone"`
  240. Role string `json:"role"`
  241. Perms string `json:"perms"`
  242. State int32 `json:"state"`
  243. }
  244. func UtilQueryMap(c *gin.Context) map[string]interface{} {
  245. query := map[string]interface{}{}
  246. q := c.Query("query")
  247. if len(q) > 0 {
  248. json.Unmarshal([]byte(q), &query)
  249. }
  250. return query
  251. }
  252. func BoolValue(value bool) *bool {
  253. return &value
  254. }
  255. func Int32Value(value int32) *int32 {
  256. return &value
  257. }
  258. func Float32Value(value float32) *float32 {
  259. return &value
  260. }
  261. func Float64Value(value float64) *float64 {
  262. return &value
  263. }