From dd1789e324a5208fda98472bae98df8c9a70e5f6 Mon Sep 17 00:00:00 2001 From: Alexandre Rodrigues Date: Thu, 17 Sep 2026 13:19:14 -0300 Subject: [PATCH] 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 --- context.go | 2 +- context_test.go | 20 ++++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/context.go b/context.go index 788b00bb..0e7cb0fa 100644 --- a/context.go +++ b/context.go @@ -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 } } diff --git a/context_test.go b/context_test.go index cef488c9..7fd2ba87 100644 --- a/context_test.go +++ b/context_test.go @@ -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)) + }) + } +}