31 lines
757 B
Go
31 lines
757 B
Go
|
|
package httpx
|
||
|
|
|
||
|
|
import (
|
||
|
|
"net/http"
|
||
|
|
)
|
||
|
|
|
||
|
|
const defaultJSONBodyLimit = 1 << 20
|
||
|
|
|
||
|
|
func JSONBodyLimit(limit int64) Middleware {
|
||
|
|
if limit <= 0 {
|
||
|
|
limit = defaultJSONBodyLimit
|
||
|
|
}
|
||
|
|
return func(next http.Handler) http.Handler {
|
||
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
|
|
switch r.Method {
|
||
|
|
case http.MethodPost, http.MethodPatch, http.MethodPut, http.MethodDelete:
|
||
|
|
r.Body = http.MaxBytesReader(w, r.Body, limit)
|
||
|
|
}
|
||
|
|
next.ServeHTTP(w, r)
|
||
|
|
})
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
func MethodNotAllowed(w http.ResponseWriter, _ *http.Request) {
|
||
|
|
WriteErrorStatus(w, http.StatusMethodNotAllowed, CodeBadRequest, "method not allowed")
|
||
|
|
}
|
||
|
|
|
||
|
|
func NotFound(w http.ResponseWriter, _ *http.Request) {
|
||
|
|
WriteError(w, NewError(CodeNotFound, "resource not found"))
|
||
|
|
}
|