response.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. package handler
  2. import (
  3. "net/http"
  4. "github.com/gin-gonic/gin"
  5. )
  6. // Response is the unified response structure.
  7. type Response struct {
  8. Code int `json:"code"`
  9. Message string `json:"message"`
  10. Data interface{} `json:"data"`
  11. }
  12. // PageResponse wraps paginated results.
  13. type PageResponse struct {
  14. Items interface{} `json:"items"`
  15. Total int64 `json:"total"`
  16. Page int `json:"page"`
  17. PageSize int `json:"page_size"`
  18. }
  19. // OK sends a 200 response with data.
  20. func OK(c *gin.Context, data interface{}) {
  21. c.JSON(http.StatusOK, Response{
  22. Code: 0,
  23. Message: "ok",
  24. Data: data,
  25. })
  26. }
  27. // Fail sends an error response.
  28. func Fail(c *gin.Context, code int, msg string) {
  29. httpStatus := http.StatusBadRequest
  30. if code == 404 {
  31. httpStatus = http.StatusNotFound
  32. } else if code == 500 {
  33. httpStatus = http.StatusInternalServerError
  34. } else if code == 501 {
  35. httpStatus = http.StatusNotImplemented
  36. }
  37. c.JSON(httpStatus, Response{
  38. Code: code,
  39. Message: msg,
  40. Data: nil,
  41. })
  42. }
  43. // PageOK sends a paginated 200 response.
  44. func PageOK(c *gin.Context, items interface{}, total int64, page, pageSize int) {
  45. c.JSON(http.StatusOK, Response{
  46. Code: 0,
  47. Message: "ok",
  48. Data: PageResponse{
  49. Items: items,
  50. Total: total,
  51. Page: page,
  52. PageSize: pageSize,
  53. },
  54. })
  55. }
  56. // parsePage extracts page and page_size from query params.
  57. // page defaults to 1, page_size defaults to 20, capped at 100.
  58. func parsePage(c *gin.Context) (page int, pageSize int, offset int) {
  59. page = 1
  60. pageSize = 20
  61. if p := c.Query("page"); p != "" {
  62. if v := parseInt(p, 1); v > 0 {
  63. page = v
  64. }
  65. }
  66. if ps := c.Query("page_size"); ps != "" {
  67. if v := parseInt(ps, 20); v > 0 {
  68. pageSize = v
  69. }
  70. }
  71. if pageSize > 100 {
  72. pageSize = 100
  73. }
  74. offset = (page - 1) * pageSize
  75. return
  76. }
  77. func parseInt(s string, def int) int {
  78. n := def
  79. for _, ch := range s {
  80. if ch < '0' || ch > '9' {
  81. return def
  82. }
  83. n = n*10 + int(ch-'0')
  84. }
  85. _ = n
  86. // simple atoi
  87. result := 0
  88. for _, ch := range s {
  89. if ch < '0' || ch > '9' {
  90. return def
  91. }
  92. result = result*10 + int(ch-'0')
  93. }
  94. return result
  95. }