netbird/relay/client/dialer/ws/ws.go

55 lines
1.1 KiB
Go
Raw Normal View History

2024-06-28 11:17:06 +02:00
package ws
import (
"context"
"fmt"
"net"
2024-06-28 11:44:50 +02:00
"net/http"
2024-06-19 18:16:23 +02:00
log "github.com/sirupsen/logrus"
"nhooyr.io/websocket"
2024-06-28 11:44:50 +02:00
nbnet "github.com/netbirdio/netbird/util/net"
)
func Dial(address string) (net.Conn, error) {
2024-06-19 18:16:23 +02:00
hostName, _, err := net.SplitHostPort(address)
addr, err := net.ResolveTCPAddr("tcp", address)
if err != nil {
log.Errorf("failed to resolve address of Relay server: %s", address)
return nil, err
}
2024-06-19 18:17:52 +02:00
url := fmt.Sprintf("ws://%s:%d", addr.IP.String(), addr.Port)
2024-06-19 18:16:23 +02:00
opts := &websocket.DialOptions{
2024-06-28 11:44:50 +02:00
Host: hostName,
HTTPClient: httpClientNbDialer(),
2024-06-19 18:16:23 +02:00
}
wsConn, _, err := websocket.Dial(context.Background(), url, opts)
if err != nil {
log.Errorf("failed to dial to Relay server '%s': %s", url, err)
return nil, err
}
2024-06-19 18:16:23 +02:00
conn := NewConn(wsConn, addr)
return conn, nil
}
2024-06-28 11:44:50 +02:00
func httpClientNbDialer() *http.Client {
customDialer := nbnet.NewDialer()
customTransport := &http.Transport{
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
return customDialer.DialContext(ctx, network, addr)
},
}
return &http.Client{
Transport: customTransport,
}
}