maxbyteshandler.go 645 B

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