ginUtils.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. "github.com/gin-gonic/gin"
  9. "mtp2_if/global/e"
  10. "mtp2_if/logger"
  11. "net/http"
  12. )
  13. // 获取数据接口
  14. type IGetData interface {
  15. GetData() ([]interface{}, error)
  16. }
  17. // 获取数据接口
  18. type IGetDataEx interface {
  19. GetDataEx() (interface{}, error)
  20. }
  21. // 数据处理接口
  22. type ICalc interface {
  23. Calc()
  24. }
  25. // 封装绑定和数据获取处理
  26. type GinUtils struct {
  27. Gin
  28. err error
  29. }
  30. // 处理参数绑定
  31. func (r *GinUtils) DoBindReq(req interface{}) {
  32. if r.err = r.C.ShouldBind(req); r.err != nil {
  33. r.Gin.Response(http.StatusBadRequest, e.INVALID_PARAMS, nil)
  34. }
  35. }
  36. // 处理数据获取, 参数obj为models结构体
  37. func (r *GinUtils) DoGetData(obj interface{}) {
  38. // 如果在参数绑定阶段有错误, 则不执行数据获取
  39. if r.err != nil {
  40. return
  41. }
  42. if v, ok := obj.(IGetData); ok {
  43. if d, err := v.GetData(); err == nil {
  44. // 执行数据处理
  45. for i := range d {
  46. if val, ok := d[i].(ICalc); ok {
  47. val.Calc()
  48. } else {
  49. break
  50. }
  51. }
  52. r.Gin.Response(http.StatusOK, e.SUCCESS, d)
  53. } else {
  54. logger.GetLogger().Errorf("query fail, %v", err)
  55. r.Gin.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
  56. }
  57. }
  58. }
  59. // 处理数据获取, 参数obj为models结构体
  60. func (r *GinUtils) DoGetDataEx(modelObj interface{}) {
  61. // 如果在参数绑定阶段有错误, 则不执行数据获取
  62. if r.err != nil {
  63. return
  64. }
  65. if v, ok := modelObj.(IGetDataEx); ok {
  66. if d, err := v.GetDataEx(); err == nil {
  67. r.Gin.Response(http.StatusOK, e.SUCCESS, d)
  68. } else {
  69. logger.GetLogger().Errorf("query fail, %v", err)
  70. r.Gin.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
  71. }
  72. }
  73. }
  74. // 生成处理GinUtils实例
  75. func NewGinUtils(c *gin.Context) *GinUtils {
  76. return &GinUtils{Gin: Gin{C: c}}
  77. }