From b593c6ea2a18f8879c22efdff00cdc61c02e41c6 Mon Sep 17 00:00:00 2001 From: eleven26 <916809498@qq.com> Date: Tue, 12 Jul 2022 20:48:41 +0800 Subject: [PATCH] Fix NegotiateFormat --- context.go | 3 ++- context_test.go | 9 +++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/context.go b/context.go index 46bf1133..93ea64c2 100644 --- a/context.go +++ b/context.go @@ -1131,7 +1131,8 @@ func (c *Context) NegotiateFormat(offered ...string) string { // 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 i := 0 - for ; i < len(accepted); i++ { + minLen := min(len(accepted), len(offer)) + for ; i < minLen; i++ { if accepted[i] == '*' || offer[i] == '*' { return offer } diff --git a/context_test.go b/context_test.go index d09b0ae1..66ff76e4 100644 --- a/context_test.go +++ b/context_test.go @@ -1311,6 +1311,15 @@ func TestContextNegotiationFormatCustom(t *testing.T) { assert.Equal(t, MIMEJSON, c.NegotiateFormat(MIMEJSON)) } +func TestContextNegotiationFormatWithShorterOfferLength(t *testing.T) { + 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, "text/*", c.NegotiateFormat("text/*")) +} + func TestContextIsAborted(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) assert.False(t, c.IsAborted())