fix(context): require complete media type matches in negotiation

`NegotiateFormat` accepts `application/json-seq` when the client only accepts `application/json`, because it treats an accepted media type as a prefix.

Require both non-wildcard media types to end at the same position. Regression cases cover both prefix directions, exact matches, and wildcard matching.

Signed-off-by: Alexandre Rodrigues <alexandre3ylf@gmail.com>
This commit is contained in:
Alexandre Rodrigues 2026-09-17 13:19:14 -03:00
parent 5c6a15f8f9
commit dd1789e324
2 changed files with 21 additions and 1 deletions

View File

@ -1474,7 +1474,7 @@ func (c *Context) NegotiateFormat(offered ...string) string {
break
}
}
if i == len(accepted) {
if i == len(accepted) && i == len(offer) {
return offer
}
}

View File

@ -4031,3 +4031,23 @@ func BenchmarkGetMapFromFormData(b *testing.B) {
})
}
}
func TestContextNegotiateFormatDoesNotMatchPrefixes(t *testing.T) {
for _, tc := range []struct {
accepted string
offered string
want string
}{
{"application/json", "application/json-seq", ""},
{"application/json-seq", "application/json", ""},
{"text/plain", "text/plaintext", ""},
{"application/json", "application/json", "application/json"},
{"application/*", "application/json-seq", "application/json-seq"},
} {
t.Run(tc.accepted+"/"+tc.offered, func(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
c.SetAccepted(tc.accepted)
assert.Equal(t, tc.want, c.NegotiateFormat(tc.offered))
})
}
}