response.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package app
  2. import (
  3. "mtp2_if/global/e"
  4. "github.com/gin-gonic/gin"
  5. )
  6. // Gin is gin.Context
  7. type Gin struct {
  8. C *gin.Context
  9. }
  10. // Response 通用Response数据结构
  11. type Response struct {
  12. Code int `json:"code"`
  13. Msg string `json:"msg"`
  14. PageInfo
  15. Data interface{} `json:"data"`
  16. }
  17. // Response setting gin.JSON
  18. func (g *Gin) Response(httpCode, errCode int, data interface{}) {
  19. g.C.JSON(httpCode, Response{
  20. Code: errCode,
  21. Msg: e.GetMsg(errCode),
  22. Data: data,
  23. })
  24. }
  25. func (g *Gin) ResponseByMsg(httpCode, errCode int, msg string, data interface{}) {
  26. g.C.JSON(httpCode, Response{
  27. Code: errCode,
  28. Msg: msg,
  29. Data: data,
  30. })
  31. }
  32. // ResponseByPage 带分页信息返回方法
  33. func (g *Gin) ResponseByPage(httpCode, errCode int, data interface{}, page PageInfo) {
  34. g.C.JSON(httpCode, Response{
  35. Code: errCode,
  36. Msg: e.GetMsg(errCode),
  37. PageInfo: page,
  38. Data: data,
  39. })
  40. }
  41. // GetPageData 获取指定分页的数据
  42. func GetPageData(datas []interface{}, pageInfo PageInfo) []interface{} {
  43. // 开始上标
  44. start := pageInfo.Page * pageInfo.PageSize
  45. // 结束下标
  46. // a := []int{1,2,3,4,5}
  47. // a[2:4] -> [3 4]
  48. end := start + pageInfo.PageSize
  49. if start <= len(datas) {
  50. // 判断结束下标是否越界
  51. if end > len(datas) {
  52. end = len(datas)
  53. }
  54. datas = datas[start:end]
  55. } else {
  56. datas = datas[0:0]
  57. }
  58. return datas
  59. }