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 package middleware
import ( import (
@ -32,13 +37,13 @@ func Decompress(opts *DecompressOptions) Middleware {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Check if the request has Content-Encoding header // Check if the request has Content-Encoding header
contentEncoding := r.Header.Get("Content-Encoding") contentEncoding := r.Header.Get("Content-Encoding")
// If not compressed, pass through // If not compressed, pass through
if contentEncoding == "" { if contentEncoding == "" {
next.ServeHTTP(w, r) next.ServeHTTP(w, r)
return return
} }
// Check if gzip encoded // Check if gzip encoded
if strings.Contains(contentEncoding, "gzip") { if strings.Contains(contentEncoding, "gzip") {
// Create a gzip reader // Create a gzip reader
@ -48,23 +53,23 @@ func Decompress(opts *DecompressOptions) Middleware {
return return
} }
defer gz.Close() defer gz.Close()
// Add limit reader if max size is specified // Add limit reader if max size is specified
var bodyReader io.Reader = gz var bodyReader io.Reader = gz
if opts.MaxSize > 0 { if opts.MaxSize > 0 {
bodyReader = io.LimitReader(gz, opts.MaxSize) bodyReader = io.LimitReader(gz, opts.MaxSize)
} }
// Replace the body with a decompressed reader // Replace the body with a decompressed reader
r.Body = io.NopCloser(bodyReader) r.Body = io.NopCloser(bodyReader)
// Remove the content-encoding header to signal that the body is now decompressed // Remove the content-encoding header to signal that the body is now decompressed
r.Header.Del("Content-Encoding") r.Header.Del("Content-Encoding")
// Adjust content length because the body has been decompressed // Adjust content length because the body has been decompressed
r.Header.Del("Content-Length") r.Header.Del("Content-Length")
} }
// Call the next handler with the decompressed body // Call the next handler with the decompressed body
next.ServeHTTP(w, r) next.ServeHTTP(w, r)
}) })
@ -74,4 +79,4 @@ func Decompress(opts *DecompressOptions) Middleware {
// DecompressDefault creates a middleware that decompresses HTTP requests with default options // DecompressDefault creates a middleware that decompresses HTTP requests with default options
func DecompressDefault() Middleware { func DecompressDefault() Middleware {
return Decompress(nil) return Decompress(nil)
} }