From f175c5a82a7ddd139678c3994678931cf8dd45e1 Mon Sep 17 00:00:00 2001 From: dawkaka Date: Sun, 17 Jul 2022 00:19:38 +0000 Subject: [PATCH] This fixes #3241 --- .gitignore | 1 + context.go | 10 +++++++++- context_test.go | 9 +++++++++ 3 files changed, 19 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index bdd50c95..3785b5fa 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ count.out test profile.out tmp.out +.vscode \ No newline at end of file diff --git a/context.go b/context.go index 46bf1133..c59dfeb2 100644 --- a/context.go +++ b/context.go @@ -1130,6 +1130,14 @@ func (c *Context) NegotiateFormat(offered ...string) string { for _, offer := range offered { // According to RFC 2616 and RFC 2396, non-ASCII characters are not allowed in headers, // therefore we can just iterate over the string without casting it into []rune + + //When the lengths are not equal, + //offer must end with '*' + //in order to avoid getting index out of range errors + if len(accepted) > len(offer) && offer[len(offer)-1] != '*' { + continue + } + i := 0 for ; i < len(accepted); i++ { if accepted[i] == '*' || offer[i] == '*' { @@ -1139,7 +1147,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 d09b0ae1..af2f8d79 100644 --- a/context_test.go +++ b/context_test.go @@ -1296,6 +1296,15 @@ func TestContextNegotiationFormatWithWildcardAccept(t *testing.T) { assert.Equal(t, c.NegotiateFormat(MIMEJSON), "") assert.Equal(t, c.NegotiateFormat(MIMEXML), "") assert.Equal(t, c.NegotiateFormat(MIMEHTML), MIMEHTML) + + c, _ = CreateTestContext(httptest.NewRecorder()) + c.Request, _ = http.NewRequest("POST", "/", nil) + c.Request.Header.Add("Accept", "text/html") + + assert.Equal(t, c.NegotiateFormat("text/htm"), "") + assert.Equal(t, c.NegotiateFormat("text/htmll"), "") + assert.Equal(t, c.NegotiateFormat("tex/*"), "") + assert.Equal(t, c.NegotiateFormat("text/html"), MIMEHTML) } func TestContextNegotiationFormatCustom(t *testing.T) {