Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions apiendpoint/api_endpoint.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,10 @@ func executeAPIEndpoint[TReq any, TResp any](w http.ResponseWriter, r *http.Requ
if r.Method != http.MethodGet {
reqData, err := io.ReadAll(r.Body)
if err != nil {
var maxBytesErr *http.MaxBytesError
if errors.As(err, &maxBytesErr) {
return apierror.NewRequestEntityTooLarge("Request entity too large.")
}
return fmt.Errorf("error reading request body: %w", err)
}

Expand Down
16 changes: 15 additions & 1 deletion apiendpoint/api_endpoint_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,19 @@ func TestMountAndServe(t *testing.T) {
requireStatusAndJSONResponse(t, http.StatusOK, &getResponse{Message: "Hello."}, bundle.recorder)
})

t.Run("MaxBytesErrorHandling", func(t *testing.T) {
t.Parallel()

mux, bundle := setup(t)

payload := mustMarshalJSON(t, &postRequest{Message: "Hello."})

req := httptest.NewRequest(http.MethodPost, "/api/post-endpoint/123", bytes.NewBuffer(payload))
req.Body = http.MaxBytesReader(bundle.recorder, io.NopCloser(bytes.NewReader(payload)), int64(len(payload)-1))
mux.ServeHTTP(bundle.recorder, req)
requireStatusAndJSONResponse(t, http.StatusRequestEntityTooLarge, &apierror.APIError{Message: "Request entity too large."}, bundle.recorder)
})

t.Run("MethodNotAllowed", func(t *testing.T) {
t.Parallel()

Expand Down Expand Up @@ -302,9 +315,10 @@ func (a *getEndpoint) Execute(_ context.Context, req *getRequest) (*getResponse,

type postEndpoint struct {
Endpoint[postRequest, postResponse]
MaxBodyBytes int64
}

func (*postEndpoint) Meta() *EndpointMeta {
func (a *postEndpoint) Meta() *EndpointMeta {
return &EndpointMeta{
Pattern: "POST /api/post-endpoint/{id}",
StatusCode: http.StatusCreated,
Expand Down
17 changes: 17 additions & 0 deletions apierror/api_error.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,23 @@ func NewNotFoundf(format string, a ...any) *NotFound {
return NewNotFound(fmt.Sprintf(format, a...))
}

//
// RequestEntityTooLarge
//

type RequestEntityTooLarge struct { //nolint:errname
APIError
}

func NewRequestEntityTooLarge(message string) *RequestEntityTooLarge {
return &RequestEntityTooLarge{
APIError: APIError{
Message: message,
StatusCode: http.StatusRequestEntityTooLarge,
},
}
}

//
// ServiceUnavailable
//
Expand Down
Loading