ginUtils.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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 ICalc interface {
  18. Calc()
  19. }
  20. // 封装绑定和数据获取处理
  21. type GinUtils struct {
  22. Gin
  23. err error
  24. }
  25. // 处理参数绑定
  26. func (r *GinUtils) DoBindReq(req interface{}) {
  27. if r.err = r.C.ShouldBind(req); r.err != nil{
  28. r.Gin.Response(http.StatusBadRequest, e.INVALID_PARAMS, nil)
  29. }
  30. }
  31. // 处理数据获取, 参数obj为models结构体
  32. func (r *GinUtils) DoGetData(obj interface{}) {
  33. // 如果在参数绑定阶段有错误, 则不执行数据获取
  34. if r.err != nil{
  35. return
  36. }
  37. if v, ok := obj.(IGetData); ok{
  38. if d, err := v.GetData(); err == nil{
  39. // 执行数据处理
  40. for i := range d {
  41. if val, ok := d[i].(ICalc); ok{
  42. val.Calc()
  43. }else{
  44. break
  45. }
  46. }
  47. r.Gin.Response(http.StatusOK, e.SUCCESS, d)
  48. }else{
  49. logger.GetLogger().Errorf("query fail, %v", err)
  50. r.Gin.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
  51. }
  52. }
  53. }