maxbyteshandler.go 726 B

12345678910111213141516171819202122232425262728
  1. package handler
  2. import (
  3. "net/http"
  4. "github.com/tal-tech/go-zero/rest/internal"
  5. )
  6. // MaxBytesHandler returns a middleware that limit reading of http request body.
  7. func MaxBytesHandler(n int64) func(http.Handler) http.Handler {
  8. if n <= 0 {
  9. return func(next http.Handler) http.Handler {
  10. return next
  11. }
  12. }
  13. return func(next http.Handler) http.Handler {
  14. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  15. if r.ContentLength > n {
  16. internal.Errorf(r, "request entity too large, limit is %d, but got %d, rejected with code %d",
  17. n, r.ContentLength, http.StatusRequestEntityTooLarge)
  18. w.WriteHeader(http.StatusRequestEntityTooLarge)
  19. } else {
  20. next.ServeHTTP(w, r)
  21. }
  22. })
  23. }
  24. }