This commit is contained in:
Vladislav Kunetskiy
2026-10-21 21:22:42 +03:00
parent f4bd361f12
commit 464db7fdd6
238 changed files with 13332 additions and 704 deletions
+35
View File
@@ -0,0 +1,35 @@
package rest
import (
"log/slog"
"net/http"
)
// bodyLimitMiddleware bounds the request body before it reaches the generated
// transport. Without it the JSON decoders read the whole body into memory before
// any schema check or authentication happens, so an oversized request to a public
// endpoint (for example POST /api/v1/users) could exhaust the replica's memory.
//
// The declared length is rejected early with 413; a client that lies about
// Content-Length is cut off by http.MaxBytesReader, which also makes the server
// close the connection instead of reading the rest.
func bodyLimitMiddleware(limit int64, log *slog.Logger, next http.Handler) http.Handler {
if limit <= 0 {
return next
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.ContentLength > limit {
logRejected(r.Context(), log, r, http.StatusRequestEntityTooLarge, nil)
writeError(r.Context(), log, w, r, http.StatusRequestEntityTooLarge)
return
}
if r.Body != nil {
r.Body = http.MaxBytesReader(w, r.Body, limit)
}
next.ServeHTTP(w, r)
})
}