ToMiddleware converts DecompressConfig to middleware or returns an error for invalid configuration
()
| 63 | |
| 64 | // ToMiddleware converts DecompressConfig to middleware or returns an error for invalid configuration |
| 65 | func (config DecompressConfig) ToMiddleware() (echo.MiddlewareFunc, error) { |
| 66 | if config.Skipper == nil { |
| 67 | config.Skipper = DefaultSkipper |
| 68 | } |
| 69 | if config.GzipDecompressPool == nil { |
| 70 | config.GzipDecompressPool = &DefaultGzipDecompressPool{} |
| 71 | } |
| 72 | // Apply secure default for decompression limit |
| 73 | if config.MaxDecompressedSize == 0 { |
| 74 | config.MaxDecompressedSize = 100 * MB |
| 75 | } |
| 76 | |
| 77 | return func(next echo.HandlerFunc) echo.HandlerFunc { |
| 78 | pool := config.GzipDecompressPool.gzipDecompressPool() |
| 79 | |
| 80 | return func(c *echo.Context) error { |
| 81 | if config.Skipper(c) { |
| 82 | return next(c) |
| 83 | } |
| 84 | |
| 85 | if c.Request().Header.Get(echo.HeaderContentEncoding) != GZIPEncoding { |
| 86 | return next(c) |
| 87 | } |
| 88 | |
| 89 | i := pool.Get() |
| 90 | gr, ok := i.(*gzip.Reader) |
| 91 | if !ok || gr == nil { |
| 92 | if err, isErr := i.(error); isErr { |
| 93 | return echo.NewHTTPError(http.StatusInternalServerError, err.Error()) |
| 94 | } |
| 95 | return echo.NewHTTPError(http.StatusInternalServerError, "unexpected type from gzip decompression pool") |
| 96 | } |
| 97 | defer pool.Put(gr) |
| 98 | |
| 99 | b := c.Request().Body |
| 100 | defer b.Close() |
| 101 | |
| 102 | if err := gr.Reset(b); err != nil { |
| 103 | if err == io.EOF { //ignore if body is empty |
| 104 | return next(c) |
| 105 | } |
| 106 | return err |
| 107 | } |
| 108 | |
| 109 | // only Close gzip reader if it was set to a proper gzip source otherwise it will panic on close. |
| 110 | defer gr.Close() |
| 111 | |
| 112 | // Apply decompression size limit to prevent zip bombs |
| 113 | if config.MaxDecompressedSize > 0 { |
| 114 | c.Request().Body = &limitedGzipReader{ |
| 115 | Reader: gr, |
| 116 | remaining: config.MaxDecompressedSize, |
| 117 | limit: config.MaxDecompressedSize, |
| 118 | } |
| 119 | } else { |
| 120 | // -1 means explicitly unlimited (not recommended) |
| 121 | c.Request().Body = gr |
| 122 | } |