Merge 34aa34892c8ca6d304585db3767b18a1cf13d588 into 0f09c3a9b4626d9fe9979cf4d0521d6ae32ab646

This commit is contained in:
Jake Wang 2026-10-13 12:32:41 +00:00 committed by GitHub
commit 5dfa31ced1
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 45 additions and 3 deletions

View File

@ -1062,9 +1062,15 @@ func (c *Context) ContentType() string {
// IsWebsocket returns true if the request headers indicate that a websocket
// handshake is being initiated by the client.
func (c *Context) IsWebsocket() bool {
if strings.Contains(strings.ToLower(c.requestHeader("Connection")), "upgrade") &&
strings.EqualFold(c.requestHeader("Upgrade"), "websocket") {
return true
if !strings.EqualFold(c.requestHeader("Upgrade"), "websocket") {
return false
}
for _, connection := range c.Request.Header.Values("Connection") {
for token := range strings.SplitSeq(connection, ",") {
if strings.EqualFold(strings.Trim(token, " \t"), "upgrade") {
return true
}
}
}
return false
}

View File

@ -3143,6 +3143,42 @@ func TestWebsocketsRequired(t *testing.T) {
assert.False(t, c.IsWebsocket())
}
func TestIsWebsocketConnectionHeaders(t *testing.T) {
for _, tt := range []struct {
name string
connection []string
upgrade string
want bool
}{
{"single token", []string{"Upgrade"}, "websocket", true},
{"mixed case", []string{"uPgRaDe"}, "WebSocket", true},
{"token list", []string{"keep-alive, Upgrade"}, "websocket", true},
{"optional whitespace", []string{"keep-alive, \tUpgrade\t "}, "websocket", true},
{"repeated fields", []string{"keep-alive", "Upgrade"}, "websocket", true},
{"empty first field", []string{"", "Upgrade"}, "websocket", true},
{"comma-only field", []string{",,"}, "websocket", false},
{"empty list entries", []string{",,Upgrade,,"}, "websocket", true},
{"token prefix", []string{"notupgrade"}, "websocket", false},
{"token suffix", []string{"upgrades"}, "websocket", false},
{"non-HTTP whitespace", []string{"\u00a0upgrade"}, "websocket", false},
{"no upgrade token", []string{"keep-alive"}, "websocket", false},
{"missing connection", nil, "websocket", false},
{"missing upgrade", []string{"Upgrade"}, "", false},
{"different protocol", []string{"Upgrade"}, "h2c", false},
} {
t.Run(tt.name, func(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
c.Request = httptest.NewRequest(http.MethodGet, "/chat", nil)
for _, connection := range tt.connection {
c.Request.Header.Add("Connection", connection)
}
c.Request.Header.Set("Upgrade", tt.upgrade)
assert.Equal(t, tt.want, c.IsWebsocket())
})
}
}
func TestContextScheme(t *testing.T) {
// TLS connection takes highest priority.
c, _ := CreateTestContext(httptest.NewRecorder())