operation.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. "strings"
  11. )
  12. var body []byte
  13. var userId uint
  14. func RecordRequestBody() gin.HandlerFunc {
  15. return func(c *gin.Context) {
  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(err)
  21. }
  22. c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(body))
  23. } else {
  24. body = nil
  25. }
  26. //TODO parse token , userId <-
  27. }
  28. }
  29. func OperationRecord() gin.HandlerFunc {
  30. return gin.LoggerWithConfig(gin.LoggerConfig{
  31. Formatter: func(param gin.LogFormatterParams) string {
  32. // 防止加载查询参数,再次过滤
  33. for _, v := range global.GVA_CONFIG.Operation.SkipPaths {
  34. if strings.Contains(param.Path, v) {
  35. return ""
  36. }
  37. }
  38. err := service.CreateSysOperationRecord(model.SysOperationRecord{
  39. Ip: param.ClientIP,
  40. Method: param.Method,
  41. Path: param.Path,
  42. Status: param.StatusCode,
  43. Latency: param.Latency,
  44. Agent: param.Request.UserAgent(),
  45. ErrorMessage: param.ErrorMessage,
  46. Body: string(body),
  47. UserId: int(userId),
  48. })
  49. if err != nil {
  50. global.GVA_LOG.Error(err)
  51. }
  52. return ""
  53. },
  54. Output: nil,
  55. SkipPaths: global.GVA_CONFIG.Operation.SkipPaths,
  56. })
  57. }