ToMiddleware converts BodyDumpConfig to middleware or returns an error for invalid configuration
()
| 71 | |
| 72 | // ToMiddleware converts BodyDumpConfig to middleware or returns an error for invalid configuration |
| 73 | func (config BodyDumpConfig) ToMiddleware() (echo.MiddlewareFunc, error) { |
| 74 | if config.Handler == nil { |
| 75 | return nil, errors.New("echo body-dump middleware requires a handler function") |
| 76 | } |
| 77 | if config.Skipper == nil { |
| 78 | config.Skipper = DefaultSkipper |
| 79 | } |
| 80 | if config.MaxRequestBytes == 0 { |
| 81 | config.MaxRequestBytes = 5 * MB |
| 82 | } |
| 83 | if config.MaxResponseBytes == 0 { |
| 84 | config.MaxResponseBytes = 5 * MB |
| 85 | } |
| 86 | |
| 87 | return func(next echo.HandlerFunc) echo.HandlerFunc { |
| 88 | return func(c *echo.Context) error { |
| 89 | if config.Skipper(c) { |
| 90 | return next(c) |
| 91 | } |
| 92 | |
| 93 | reqBuf := bodyDumpBufferPool.Get().(*bytes.Buffer) |
| 94 | reqBuf.Reset() |
| 95 | defer bodyDumpBufferPool.Put(reqBuf) |
| 96 | |
| 97 | var bodyReader io.Reader = c.Request().Body |
| 98 | if config.MaxRequestBytes > 0 { |
| 99 | bodyReader = io.LimitReader(c.Request().Body, config.MaxRequestBytes) |
| 100 | } |
| 101 | _, readErr := io.Copy(reqBuf, bodyReader) |
| 102 | if readErr != nil && readErr != io.EOF { |
| 103 | return readErr |
| 104 | } |
| 105 | if config.MaxRequestBytes > 0 { |
| 106 | // Drain any remaining body data to prevent connection issues |
| 107 | _, _ = io.Copy(io.Discard, c.Request().Body) |
| 108 | _ = c.Request().Body.Close() |
| 109 | } |
| 110 | |
| 111 | reqBody := make([]byte, reqBuf.Len()) |
| 112 | copy(reqBody, reqBuf.Bytes()) |
| 113 | c.Request().Body = io.NopCloser(bytes.NewReader(reqBody)) |
| 114 | |
| 115 | // response part |
| 116 | resBuf := bodyDumpBufferPool.Get().(*bytes.Buffer) |
| 117 | resBuf.Reset() |
| 118 | defer bodyDumpBufferPool.Put(resBuf) |
| 119 | |
| 120 | var respWriter io.Writer |
| 121 | if config.MaxResponseBytes > 0 { |
| 122 | respWriter = &limitedWriter{ |
| 123 | response: c.Response(), |
| 124 | dumpBuf: resBuf, |
| 125 | limit: config.MaxResponseBytes, |
| 126 | } |
| 127 | } else { |
| 128 | respWriter = io.MultiWriter(c.Response(), resBuf) |
| 129 | } |
| 130 | writer := &bodyDumpResponseWriter{ |