Skip to content

Commit 770e618

Browse files
authored
fix: content type validation should be case insensitive (#1052)
1 parent fd8148e commit 770e618

2 files changed

Lines changed: 31 additions & 4 deletions

File tree

‎api.go‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -352,7 +352,7 @@ func (a *api) Unmarshal(contentType string, data []byte, v any) error {
352352
return err
353353
}
354354

355-
ct := contentType[start:end]
355+
ct := strings.ToLower(contentType[start:end])
356356
if ct == "" {
357357
// Default to assume JSON since this is an API.
358358
ct = "application/json"
@@ -396,14 +396,15 @@ func (a *api) Transform(ctx Context, status string, v any) (any, error) {
396396
}
397397

398398
func (a *api) Marshal(w io.Writer, ct string, v any) error {
399-
f, ok := a.formats[ct]
399+
lower := strings.ToLower(ct)
400+
f, ok := a.formats[lower]
400401
if !ok {
401-
start, end, err := parseContentType(ct)
402+
start, end, err := parseContentType(lower)
402403
if err != nil {
403404
return err
404405
}
405406

406-
f, ok = a.formats[ct[start:end]]
407+
f, ok = a.formats[lower[start:end]]
407408
}
408409
if !ok {
409410
return fmt.Errorf("%w: %s", ErrUnknownContentType, ct)

‎huma_test.go‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -923,6 +923,32 @@ func TestFeatures(t *testing.T) {
923923
// Headers: map[string]string{"Content-Type": "application/json"},
924924
Body: `{"name":"foo"}`,
925925
},
926+
{
927+
// Media types are case-insensitive (RFC 9110 §8.3.1). A client sending
928+
// e.g. `Application/Json` must still be matched to the registered
929+
// `application/json` format rather than rejected with 415.
930+
Name: "request-body-content-type-case-insensitive",
931+
Register: func(t *testing.T, api huma.API) {
932+
huma.Register(api, huma.Operation{
933+
Method: http.MethodPut,
934+
Path: "/body",
935+
}, func(ctx context.Context, input *struct {
936+
Body struct {
937+
Name string `json:"name"`
938+
}
939+
}) (*struct{}, error) {
940+
assert.Equal(t, "foo", input.Body.Name)
941+
return nil, nil
942+
})
943+
},
944+
Method: http.MethodPut,
945+
URL: "/body",
946+
Headers: map[string]string{"Content-Type": "Application/Json; charset=UTF-8"},
947+
Body: `{"name":"foo"}`,
948+
Assert: func(t *testing.T, resp *httptest.ResponseRecorder) {
949+
assert.Equal(t, http.StatusNoContent, resp.Code, resp.Body.String())
950+
},
951+
},
926952
{
927953
Name: "request-body-embed",
928954
Register: func(t *testing.T, api huma.API) {

0 commit comments

Comments
 (0)