request_body_limit_test.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package handler
  2. import (
  3. "bytes"
  4. "io"
  5. "net/http"
  6. "net/http/httptest"
  7. "testing"
  8. "github.com/Wei-Shaw/sub2api/internal/server/middleware"
  9. "github.com/gin-gonic/gin"
  10. "github.com/stretchr/testify/require"
  11. )
  12. func TestRequestBodyLimitTooLarge(t *testing.T) {
  13. gin.SetMode(gin.TestMode)
  14. limit := int64(16)
  15. router := gin.New()
  16. router.Use(middleware.RequestBodyLimit(limit))
  17. router.POST("/test", func(c *gin.Context) {
  18. _, err := io.ReadAll(c.Request.Body)
  19. if err != nil {
  20. if maxErr, ok := extractMaxBytesError(err); ok {
  21. c.JSON(http.StatusRequestEntityTooLarge, gin.H{
  22. "error": buildBodyTooLargeMessage(maxErr.Limit),
  23. })
  24. return
  25. }
  26. c.JSON(http.StatusBadRequest, gin.H{
  27. "error": "read_failed",
  28. })
  29. return
  30. }
  31. c.JSON(http.StatusOK, gin.H{"ok": true})
  32. })
  33. payload := bytes.Repeat([]byte("a"), int(limit+1))
  34. req := httptest.NewRequest(http.MethodPost, "/test", bytes.NewReader(payload))
  35. recorder := httptest.NewRecorder()
  36. router.ServeHTTP(recorder, req)
  37. require.Equal(t, http.StatusRequestEntityTooLarge, recorder.Code)
  38. require.Contains(t, recorder.Body.String(), buildBodyTooLargeMessage(limit))
  39. }