request_body_limit.go 959 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package handler
  2. import (
  3. "errors"
  4. "fmt"
  5. "net/http"
  6. "github.com/Wei-Shaw/sub2api/internal/config"
  7. pkghttputil "github.com/Wei-Shaw/sub2api/internal/pkg/httputil"
  8. )
  9. func extractMaxBytesError(err error) (*http.MaxBytesError, bool) {
  10. var maxErr *http.MaxBytesError
  11. if errors.As(err, &maxErr) {
  12. return maxErr, true
  13. }
  14. return nil, false
  15. }
  16. func formatBodyLimit(limit int64) string {
  17. const mb = 1024 * 1024
  18. if limit >= mb {
  19. return fmt.Sprintf("%dMB", limit/mb)
  20. }
  21. return fmt.Sprintf("%dB", limit)
  22. }
  23. func buildBodyTooLargeMessage(limit int64) string {
  24. return fmt.Sprintf("Request body too large, limit is %s", formatBodyLimit(limit))
  25. }
  26. func readLenientJSONRequestBodyWithPrealloc(req *http.Request, cfg *config.Config) ([]byte, error) {
  27. return pkghttputil.ReadLenientJSONRequestBodyWithPrealloc(req, gatewayMaxBodySize(cfg))
  28. }
  29. func gatewayMaxBodySize(cfg *config.Config) int64 {
  30. if cfg == nil {
  31. return 0
  32. }
  33. return cfg.Gateway.MaxBodySize
  34. }