Enhance WebSocket upgrade detection in Mihomo
Publish telemt-api gateway Docker image / test (push) Successful in 26s
Publish telemt-api gateway Docker image / build-and-push (push) Successful in 1m57s

- Updated the `isWebSocketUpgrade` function to improve handling of WebSocket upgrade requests by considering the presence of the "Sec-WebSocket-Key" header as a strong indicator.
- Added a new test case in `TestIsWebSocketUpgrade` to validate the detection logic for requests with the "Sec-WebSocket-Key" header, ensuring comprehensive test coverage.
This commit is contained in:
Denozordec
2026-03-31 10:28:06 +07:00
parent 1686840b0e
commit 77a6c1e31e
2 changed files with 14 additions and 4 deletions
+8 -4
View File
@@ -36,10 +36,14 @@ func isWebSocketUpgrade(r *http.Request) bool {
if r == nil {
return false
}
// Some clients/proxies pass comma-separated tokens or extra spaces.
// Treat request as WS only when both headers contain required upgrade tokens.
return headerHasToken(r.Header, "Connection", "upgrade") &&
headerHasToken(r.Header, "Upgrade", "websocket")
// Be tolerant to proxy/header quirks:
// - RFC path: Connection: upgrade + Upgrade: websocket
// - Fallback: Sec-WebSocket-Key presence strongly indicates WS handshake.
if headerHasToken(r.Header, "Upgrade", "websocket") &&
headerHasToken(r.Header, "Connection", "upgrade") {
return true
}
return strings.TrimSpace(r.Header.Get("Sec-WebSocket-Key")) != ""
}
func headerHasToken(h http.Header, key, token string) bool {
+6
View File
@@ -53,4 +53,10 @@ func TestIsWebSocketUpgrade(t *testing.T) {
if isWebSocketUpgrade(r2) {
t.Fatal("expected non-websocket when Connection lacks upgrade")
}
r3 := httptest.NewRequest(http.MethodGet, "http://gw/api/mtg/mihomo/traffic", nil)
r3.Header.Set("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==")
if !isWebSocketUpgrade(r3) {
t.Fatal("expected websocket upgrade when Sec-WebSocket-Key is present")
}
}