This commit is contained in:
dawkaka 2022-07-17 00:19:38 +00:00
parent b57163a0e4
commit f175c5a82a
3 changed files with 19 additions and 1 deletions

1
.gitignore vendored
View File

@ -5,3 +5,4 @@ count.out
test test
profile.out profile.out
tmp.out tmp.out
.vscode

View File

@ -1130,6 +1130,14 @@ func (c *Context) NegotiateFormat(offered ...string) string {
for _, offer := range offered { for _, offer := range offered {
// According to RFC 2616 and RFC 2396, non-ASCII characters are not allowed in headers, // 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 // 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 i := 0
for ; i < len(accepted); i++ { for ; i < len(accepted); i++ {
if accepted[i] == '*' || offer[i] == '*' { if accepted[i] == '*' || offer[i] == '*' {
@ -1139,7 +1147,7 @@ func (c *Context) NegotiateFormat(offered ...string) string {
break break
} }
} }
if i == len(accepted) { if i == len(accepted) && i == len(offer) {
return offer return offer
} }
} }

View File

@ -1296,6 +1296,15 @@ func TestContextNegotiationFormatWithWildcardAccept(t *testing.T) {
assert.Equal(t, c.NegotiateFormat(MIMEJSON), "") assert.Equal(t, c.NegotiateFormat(MIMEJSON), "")
assert.Equal(t, c.NegotiateFormat(MIMEXML), "") assert.Equal(t, c.NegotiateFormat(MIMEXML), "")
assert.Equal(t, c.NegotiateFormat(MIMEHTML), MIMEHTML) 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) { func TestContextNegotiationFormatCustom(t *testing.T) {