common.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package middleware
  2. import (
  3. "bytes"
  4. "fmt"
  5. "github.com/gin-gonic/gin"
  6. "hongze/hongze_yb/utils"
  7. "io"
  8. "net/http"
  9. "strconv"
  10. )
  11. type Common struct{}
  12. // RequestLog
  13. // @Description: 请求参数日志
  14. // @author: Roc
  15. // @receiver common
  16. // @datetime 2024-10-31 10:19:36
  17. // @param c *gin.Context
  18. func (common *Common) RequestLog(c *gin.Context) {
  19. // 读取请求体
  20. body, err := io.ReadAll(c.Request.Body)
  21. if err != nil {
  22. //log.Printf("Error reading request body: %v", err)
  23. c.AbortWithStatus(http.StatusInternalServerError)
  24. return
  25. }
  26. // 将请求地址添加到上下文的日志中
  27. utils.SetBridgeLogListByClaims(c, fmt.Sprint("Url:", c.Request.RequestURI))
  28. // 将请求参数添加到上下文的日志中
  29. utils.SetBridgeLogListByClaims(c, fmt.Sprint("RequestBody:", string(body)))
  30. // 将请求体恢复到原始状态
  31. c.Request.Body = io.NopCloser(bytes.NewBuffer(body))
  32. c.Next()
  33. }
  34. // Page
  35. // @Description: 分页参数
  36. // @author: Roc
  37. // @receiver common
  38. // @datetime 2024-10-31 10:19:36
  39. // @param c *gin.Context
  40. func (common *Common) Page(c *gin.Context) {
  41. var currPage, pageSize int
  42. reqPage := c.DefaultQuery("curr_page", "0")
  43. currPage, _ = strconv.Atoi(reqPage)
  44. if currPage <= 0 {
  45. currPage = 1
  46. }
  47. reqPageSize := c.DefaultQuery("page_size", "0")
  48. pageSize, _ = strconv.Atoi(reqPageSize)
  49. if pageSize <= 0 {
  50. pageSize = 20
  51. }
  52. c.Set("curr_page", currPage)
  53. c.Set("page_size", pageSize)
  54. c.Next()
  55. }
  56. // Common2 公共中间件
  57. func Common2() gin.HandlerFunc {
  58. return func(c *gin.Context) {
  59. var currPage, pageSize int
  60. reqPage := c.DefaultQuery("curr_page", "0")
  61. currPage, _ = strconv.Atoi(reqPage)
  62. if currPage <= 0 {
  63. currPage = 1
  64. }
  65. reqPageSize := c.DefaultQuery("page_size", "0")
  66. pageSize, _ = strconv.Atoi(reqPageSize)
  67. if pageSize <= 0 {
  68. pageSize = 20
  69. }
  70. c.Set("curr_page", currPage)
  71. c.Set("page_size", pageSize)
  72. c.Next()
  73. }
  74. }