2020-07-29 18:00:04 +08:00
|
|
|
package handler
|
2020-07-26 17:09:05 +08:00
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
|
2022-01-04 15:51:32 +08:00
|
|
|
"github.com/zeromicro/go-zero/rest/internal"
|
2020-07-26 17:09:05 +08:00
|
|
|
)
|
|
|
|
|
2021-03-01 19:15:35 +08:00
|
|
|
// MaxBytesHandler returns a middleware that limit reading of http request body.
|
2020-07-26 17:09:05 +08:00
|
|
|
func MaxBytesHandler(n int64) func(http.Handler) http.Handler {
|
|
|
|
if n <= 0 {
|
|
|
|
return func(next http.Handler) http.Handler {
|
|
|
|
return next
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return func(next http.Handler) http.Handler {
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
if r.ContentLength > n {
|
2020-07-29 18:00:04 +08:00
|
|
|
internal.Errorf(r, "request entity too large, limit is %d, but got %d, rejected with code %d",
|
2020-07-26 17:09:05 +08:00
|
|
|
n, r.ContentLength, http.StatusRequestEntityTooLarge)
|
|
|
|
w.WriteHeader(http.StatusRequestEntityTooLarge)
|
|
|
|
} else {
|
|
|
|
next.ServeHTTP(w, r)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|