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.

68 lines
1.5 KiB

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