mirror of
https://github.com/gin-gonic/gin.git
synced 2026-11-23 11:33:37 +08:00
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:
parent
5c6a15f8f9
commit
dd1789e324
@ -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
|
||||
}
|
||||
}
|
||||
|
||||
@ -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))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user