From fd8a51eb979ab0fa87e6eb58b0e4f14428f31fd9 Mon Sep 17 00:00:00 2001 From: Faraz Fazli Date: Fri, 31 Mar 2023 07:29:16 -0400 Subject: [PATCH] Request size middleware (#808) (#809) --- middleware/request_size.go | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 middleware/request_size.go diff --git a/middleware/request_size.go b/middleware/request_size.go new file mode 100644 index 00000000..678248c4 --- /dev/null +++ b/middleware/request_size.go @@ -0,0 +1,18 @@ +package middleware + +import ( + "net/http" +) + +// RequestSize is a middleware that will limit request sizes to a specified +// number of bytes. It uses MaxBytesReader to do so. +func RequestSize(bytes int64) func(http.Handler) http.Handler { + f := func(h http.Handler) http.Handler { + fn := func(w http.ResponseWriter, r *http.Request) { + r.Body = http.MaxBytesReader(w, r.Body, bytes) + h.ServeHTTP(w, r) + } + return http.HandlerFunc(fn) + } + return f +}