Wraps request body with http.MaxBytesReader to limit incoming payload size. Without this, any endpoint accepting a body is vulnerable to large uploads consuming all available memory. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
16 lines
487 B
Go
16 lines
487 B
Go
package server
|
|
|
|
import "net/http"
|
|
|
|
// MaxBodySize returns a middleware that limits the size of incoming request
|
|
// bodies. If the body exceeds n bytes, the server returns 413 Request Entity
|
|
// Too Large. It wraps the body with http.MaxBytesReader.
|
|
func MaxBodySize(n int64) Middleware {
|
|
return func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
r.Body = http.MaxBytesReader(w, r.Body, n)
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
}
|