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. "time"
  14. )
  15. func OperationRecord() gin.HandlerFunc {
  16. return func(c *gin.Context) {
  17. var body []byte
  18. var userId int
  19. if c.Request.Method != http.MethodGet {
  20. var err error
  21. body, err = ioutil.ReadAll(c.Request.Body)
  22. if err != nil {
  23. global.GVA_LOG.Error("read body from request error:", zap.Any("err", err))
  24. } else {
  25. c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(body))
  26. }
  27. }
  28. if claims, ok := c.Get("claims"); ok {
  29. waitUse := claims.(*request.CustomClaims)
  30. userId = int(waitUse.ID)
  31. } else {
  32. id, err := strconv.Atoi(c.Request.Header.Get("x-user-id"))
  33. if err != nil {
  34. userId = 0
  35. }
  36. userId = id
  37. }
  38. record := model.SysOperationRecord{
  39. Ip: c.ClientIP(),
  40. Method: c.Request.Method,
  41. Path: c.Request.URL.Path,
  42. Agent: c.Request.UserAgent(),
  43. Body: string(body),
  44. UserID: userId,
  45. }
  46. // 存在某些未知错误 TODO
  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. }