body.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package middleware
  2. import (
  3. "bytes"
  4. "crawler/model"
  5. "fmt"
  6. "io/ioutil"
  7. "github.com/gin-gonic/gin"
  8. )
  9. type BodyLogWriter struct {
  10. gin.ResponseWriter
  11. body *bytes.Buffer
  12. }
  13. func (w BodyLogWriter) Write(b []byte) (int, error) {
  14. w.body.Write(b)
  15. return w.ResponseWriter.Write(b)
  16. }
  17. func GinBodyResponse() gin.HandlerFunc {
  18. return func(c *gin.Context) {
  19. var (
  20. bodyBytes []byte
  21. processLog = new(model.ProcessLogModel)
  22. )
  23. if c.Request.Body != nil {
  24. bodyBytes, _ = ioutil.ReadAll(c.Request.Body)
  25. }
  26. c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
  27. blw := &BodyLogWriter{body: bytes.NewBufferString(""), ResponseWriter: c.Writer}
  28. c.Writer = blw
  29. c.Next()
  30. /*
  31. fmt.Printf(
  32. "Send HTTP response, req uri: %v, method: %v, body: %v, resp code: %v, body: %v",
  33. c.Request.RequestURI, c.Request.Method, string(bodyBytes), c.Writer.Status(), blw.body.String(),
  34. )
  35. */
  36. fmt.Printf(
  37. "Send HTTP response, req uri: %v, method: %v, resp code: %v",
  38. c.Request.RequestURI, c.Request.Method, c.Writer.Status(),
  39. )
  40. processLog.Path = c.Request.RequestURI
  41. processLog.Code = c.Writer.Status()
  42. processLog.Method = c.Request.Method
  43. processLog.RawQuery = c.Request.URL.RawQuery
  44. processLog.Response = blw.body.String()
  45. processLog.Request = string(bodyBytes)
  46. processLog.Save()
  47. }
  48. }