response.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. return
  25. }
  26. // ResponseByPage 带分页信息返回方法
  27. func (g *Gin) ResponseByPage(httpCode, errCode int, data interface{}, page PageInfo) {
  28. g.C.JSON(httpCode, Response{
  29. Code: errCode,
  30. Msg: e.GetMsg(errCode),
  31. PageInfo: page,
  32. Data: data,
  33. })
  34. return
  35. }
  36. // GetPageData 获取指定分页的数据
  37. func GetPageData(datas []interface{}, pageInfo PageInfo) []interface{} {
  38. // 开始上标
  39. start := pageInfo.Page * pageInfo.PageSize
  40. // 结束下标
  41. // a := []int{1,2,3,4,5}
  42. // a[2:4] -> [3 4]
  43. end := start + pageInfo.PageSize
  44. if start <= len(datas) {
  45. // 判断结束下标是否越界
  46. if end > len(datas) {
  47. end = len(datas)
  48. }
  49. datas = datas[start:end]
  50. } else {
  51. datas = datas[0:0]
  52. }
  53. return datas
  54. }