Decompression notes.

This commit is contained in:
Christian Galo 2025-05-15 15:16:51 -05:00
parent adf3db4d72
commit e304712923

View File

@ -1,3 +1,8 @@
// NOTE: This middleware is not needed for most applications.
// Browsers and typical HTTP clients do not compress request bodies,
// so decompressing requests is unnecessary unless you explicitly expect
// gzip-compressed payloads from known clients.
package middleware
import (
@ -32,13 +37,13 @@ func Decompress(opts *DecompressOptions) Middleware {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Check if the request has Content-Encoding header
contentEncoding := r.Header.Get("Content-Encoding")
// If not compressed, pass through
if contentEncoding == "" {
next.ServeHTTP(w, r)
return
}
// Check if gzip encoded
if strings.Contains(contentEncoding, "gzip") {
// Create a gzip reader
@ -48,23 +53,23 @@ func Decompress(opts *DecompressOptions) Middleware {
return
}
defer gz.Close()
// Add limit reader if max size is specified
var bodyReader io.Reader = gz
if opts.MaxSize > 0 {
bodyReader = io.LimitReader(gz, opts.MaxSize)
}
// Replace the body with a decompressed reader
r.Body = io.NopCloser(bodyReader)
// Remove the content-encoding header to signal that the body is now decompressed
r.Header.Del("Content-Encoding")
// Adjust content length because the body has been decompressed
r.Header.Del("Content-Length")
}
// Call the next handler with the decompressed body
next.ServeHTTP(w, r)
})
@ -74,4 +79,4 @@ func Decompress(opts *DecompressOptions) Middleware {
// DecompressDefault creates a middleware that decompresses HTTP requests with default options
func DecompressDefault() Middleware {
return Decompress(nil)
}
}