common.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. // Common 公共中间件
  12. type Common struct{}
  13. // RequestLog
  14. // @Description: 请求参数日志
  15. // @author: Roc
  16. // @receiver common
  17. // @datetime 2024-10-31 10:19:36
  18. // @param c *gin.Context
  19. func (common *Common) RequestLog(c *gin.Context) {
  20. // 读取请求体
  21. body, err := io.ReadAll(c.Request.Body)
  22. if err != nil {
  23. //log.Printf("Error reading request body: %v", err)
  24. c.AbortWithStatus(http.StatusInternalServerError)
  25. return
  26. }
  27. // 将请求地址添加到上下文的日志中
  28. utils.SetContextLogListByClaims(c, fmt.Sprint("Url:", c.Request.RequestURI))
  29. // 将请求参数添加到上下文的日志中
  30. utils.SetContextLogListByClaims(c, fmt.Sprint("RequestBody:", string(body)))
  31. // 将请求体恢复到原始状态
  32. c.Request.Body = io.NopCloser(bytes.NewBuffer(body))
  33. c.Next()
  34. }
  35. // Page
  36. // @Description: 分页参数
  37. // @author: Roc
  38. // @receiver common
  39. // @datetime 2024-10-31 10:19:36
  40. // @param c *gin.Context
  41. func (common *Common) Page(c *gin.Context) {
  42. var currPage, pageSize int
  43. reqPage := c.DefaultQuery("curr_page", "0")
  44. currPage, _ = strconv.Atoi(reqPage)
  45. if currPage <= 0 {
  46. currPage = 1
  47. }
  48. reqPageSize := c.DefaultQuery("page_size", "0")
  49. pageSize, _ = strconv.Atoi(reqPageSize)
  50. if pageSize <= 0 {
  51. pageSize = 20
  52. }
  53. c.Set("curr_page", currPage)
  54. c.Set("page_size", pageSize)
  55. c.Next()
  56. }