ginUtils.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /**
  2. * @Author: zou.yingbin
  3. * @Create : 2021/1/25 9:42
  4. * @Modify : 2021/1/25 9:42
  5. */
  6. package app
  7. import (
  8. "mtp2_if/global/e"
  9. "mtp2_if/logger"
  10. "net/http"
  11. )
  12. // 获取数据接口
  13. type IGetData interface {
  14. GetData()([]interface{}, error)
  15. }
  16. // 获取数据接口
  17. type IGetDataEx interface {
  18. GetDataEx()(interface{}, error)
  19. }
  20. // 数据处理接口
  21. type ICalc interface {
  22. Calc()
  23. }
  24. // 封装绑定和数据获取处理
  25. type GinUtils struct {
  26. Gin
  27. err error
  28. }
  29. // 处理参数绑定
  30. func (r *GinUtils) DoBindReq(req interface{}) {
  31. if r.err = r.C.ShouldBind(req); r.err != nil{
  32. r.Gin.Response(http.StatusBadRequest, e.INVALID_PARAMS, nil)
  33. }
  34. }
  35. // 处理数据获取, 参数obj为models结构体
  36. func (r *GinUtils) DoGetData(obj interface{}) {
  37. // 如果在参数绑定阶段有错误, 则不执行数据获取
  38. if r.err != nil{
  39. return
  40. }
  41. if v, ok := obj.(IGetData); ok{
  42. if d, err := v.GetData(); err == nil{
  43. // 执行数据处理
  44. for i := range d {
  45. if val, ok := d[i].(ICalc); ok{
  46. val.Calc()
  47. }else{
  48. break
  49. }
  50. }
  51. r.Gin.Response(http.StatusOK, e.SUCCESS, d)
  52. }else{
  53. logger.GetLogger().Errorf("query fail, %v", err)
  54. r.Gin.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
  55. }
  56. }
  57. }
  58. // 处理数据获取, 参数obj为models结构体
  59. func (r *GinUtils) DoGetDataEx(modelObj interface{}) {
  60. // 如果在参数绑定阶段有错误, 则不执行数据获取
  61. if r.err != nil{
  62. return
  63. }
  64. if v, ok := modelObj.(IGetDataEx); ok{
  65. if d, err := v.GetDataEx(); err == nil{
  66. r.Gin.Response(http.StatusOK, e.SUCCESS, d)
  67. }else{
  68. logger.GetLogger().Errorf("query fail, %v", err)
  69. r.Gin.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
  70. }
  71. }
  72. }