refactor: extract lease ID logic into getLeaseID function and improve URL parsing
- Added net/url import for proper URI parsing in CreateConnection - Renamed parameter from 'url' to 'uri' for clarity - Introduced getLeaseID function to extract and normalize hostname to uppercase ID - Updated ServeHTTP to use getLeaseID, removing code duplication - Set WebSocket URL scheme to 'ws' and host to lease ID for correct dialing - Ensures consistent lease ID generation and better error handling for invalid URIs
lemon-mint committed
Nov 1, 2025 at 02:16 UTC
fa5a26778a1849f9626c39f72ea20e85f240e67f
1 file changed
+24
-11
cmd/webclient/main_js.go
+24
-11
@@ -11,6 +11,7 @@ import (
11
"mime"
12
"net"
13
"net/http"
14
+ "net/url"
15
"os"
16
"runtime"
17
"strings"
@@ -109,14 +110,23 @@ func generateConnID() string {
110
return hex.EncodeToString(b)
111
}
112
112
-func (m *WebSocketManager) CreateConnection(url string, protocols []string) (*WSConnection, string, error) {
113
+func (m *WebSocketManager) CreateConnection(uri string, protocols []string) (*WSConnection, string, error) {
114
+ u, err := url.Parse(uri)
115
+ if err != nil {
116
+ return nil, "", err
117
+ }
118
+ id := getLeaseID(u.Hostname())
119
+
120
+ u.Scheme = "ws"
121
+ u.Host = id
122
+
123
// Parse URL to extract host for rdDialer
124
dialer := websocket.Dialer{
125
NetDialContext: rdDialer,
126
Subprotocols: protocols,
127
}
128
119
- conn, resp, err := dialer.Dial(url, nil)
129
+ conn, resp, err := dialer.Dial(u.String(), nil)
130
if err != nil {
131
return nil, "", err
132
}
@@ -224,6 +234,17 @@ func IsHTMLContentType(contentType string) bool {
234
return mediaType == "text/html"
235
}
236
237
+func getLeaseID(hostname string) string {
238
+ host, err := idna.ToUnicode(hostname)
239
+ if err != nil {
240
+ host = hostname
241
+ }
242
+ id := strings.Split(host, ".")[0]
243
+ id = strings.TrimSpace(id)
244
+ id = strings.ToUpper(id)
245
+ return id
246
+}
247
+
248
func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
249
// Handle WebSocket polyfill endpoints
250
if strings.HasPrefix(r.URL.Path, "/sw-cgi/websocket/") {
@@ -233,16 +254,8 @@ func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
254
255
log.Info().Msgf("Proxying request to %s", r.URL.String())
256
236
- host, err := idna.ToUnicode(r.URL.Hostname())
237
- if err != nil {
238
- host = r.URL.Hostname()
239
- }
240
- id := strings.Split(host, ".")[0]
241
- id = strings.TrimSpace(id)
242
- id = strings.ToUpper(id)
243
-
257
r = r.Clone(context.Background())
245
- r.URL.Host = id
258
+ r.URL.Host = getLeaseID(r.URL.Hostname())
259
r.URL.Scheme = "http"
260
261
resp, err := client.Do(r)