20 lines
627 B
Go
20 lines
627 B
Go
package middleware
|
|
|
|
import "net/http"
|
|
|
|
// BodyLimit caps request body size. Returns 413 if exceeded.
|
|
func BodyLimit(maxBytes int64) func(http.Handler) http.Handler {
|
|
return func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if r.ContentLength > maxBytes {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(http.StatusRequestEntityTooLarge)
|
|
_, _ = w.Write([]byte(`{"error":"PayloadTooLarge","detail":"request body exceeds limit"}`))
|
|
return
|
|
}
|
|
r.Body = http.MaxBytesReader(w, r.Body, maxBytes)
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
}
|