You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
1.9 KiB

  1. package middleware
  2. import (
  3. "bytes"
  4. "gin-vue-admin/global"
  5. "gin-vue-admin/model"
  6. "gin-vue-admin/model/request"
  7. "gin-vue-admin/service"
  8. "github.com/gin-gonic/gin"
  9. "go.uber.org/zap"
  10. "io/ioutil"
  11. "net/http"
  12. "strconv"
  13. "strings"
  14. "time"
  15. )
  16. func OperationRecord() gin.HandlerFunc {
  17. return func(c *gin.Context) {
  18. var body []byte
  19. var userId int
  20. if c.Request.Method != http.MethodGet {
  21. var err error
  22. body, err = ioutil.ReadAll(c.Request.Body)
  23. if err != nil {
  24. global.GVA_LOG.Error("read body from request error:", zap.Any("err", err))
  25. } else {
  26. c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(body))
  27. }
  28. }
  29. if claims, ok := c.Get("claims"); ok {
  30. waitUse := claims.(*request.CustomClaims)
  31. userId = int(waitUse.ID)
  32. }else {
  33. id, err := strconv.Atoi(c.Request.Header.Get("x-user-id"))
  34. if err != nil {
  35. userId = 0
  36. }
  37. userId = id
  38. }
  39. record := model.SysOperationRecord{
  40. Ip: c.ClientIP(),
  41. Method: c.Request.Method,
  42. Path: c.Request.URL.Path,
  43. Agent: c.Request.UserAgent(),
  44. Body: string(body),
  45. UserID: userId,
  46. }
  47. values := c.Request.Header.Values("content-type")
  48. if len(values) >0 && strings.Contains(values[0], "boundary") {
  49. record.Body = "file"
  50. }
  51. writer := responseBodyWriter{
  52. ResponseWriter: c.Writer,
  53. body: &bytes.Buffer{},
  54. }
  55. c.Writer = writer
  56. now := time.Now()
  57. c.Next()
  58. latency := time.Now().Sub(now)
  59. record.ErrorMessage = c.Errors.ByType(gin.ErrorTypePrivate).String()
  60. record.Status = c.Writer.Status()
  61. record.Latency = latency
  62. record.Resp = writer.body.String()
  63. if err := service.CreateSysOperationRecord(record); err != nil {
  64. global.GVA_LOG.Error("create operation record error:", zap.Any("err", err))
  65. }
  66. }
  67. }
  68. type responseBodyWriter struct {
  69. gin.ResponseWriter
  70. body *bytes.Buffer
  71. }
  72. func (r responseBodyWriter) Write(b []byte) (int, error) {
  73. r.body.Write(b)
  74. return r.ResponseWriter.Write(b)
  75. }