mirror of
https://github.com/Xevion/go-ha.git
synced 2026-01-31 00:24:22 -06:00
feat: support secure connections
This commit is contained in:
+18
-2
@@ -16,8 +16,24 @@ type HttpClient struct {
|
||||
}
|
||||
|
||||
func NewHttpClient(ip, port, token string) *HttpClient {
|
||||
url := fmt.Sprintf("http://%s:%s/api", ip, port)
|
||||
return &HttpClient{url, token}
|
||||
return ClientFromUri(
|
||||
fmt.Sprintf("http://%s:%s/api", ip, port),
|
||||
token,
|
||||
)
|
||||
}
|
||||
|
||||
func NewHttpsClient(ip, port, token string) *HttpClient {
|
||||
return ClientFromUri(
|
||||
fmt.Sprintf("https://%s:%s/api", ip, port),
|
||||
token,
|
||||
)
|
||||
}
|
||||
|
||||
func ClientFromUri(uri, token string) *HttpClient {
|
||||
return &HttpClient{
|
||||
uri,
|
||||
token,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *HttpClient) GetState(entityId string) ([]byte, error) {
|
||||
|
||||
@@ -50,14 +50,24 @@ func ReadMessage(conn *websocket.Conn, ctx context.Context) ([]byte, error) {
|
||||
}
|
||||
|
||||
func SetupConnection(ip, port, authToken string) (*websocket.Conn, context.Context, context.CancelFunc, error) {
|
||||
uri := fmt.Sprintf("ws:///%s:%s/api/websocket", ip, port)
|
||||
return ConnectionFromUri(uri, authToken)
|
||||
}
|
||||
|
||||
func SetupSecureConnection(ip, port, authToken string) (*websocket.Conn, context.Context, context.CancelFunc, error) {
|
||||
uri := fmt.Sprintf("wss://%s:%s/api/websocket", ip, port)
|
||||
return ConnectionFromUri(uri, authToken)
|
||||
}
|
||||
|
||||
func ConnectionFromUri(uri, authToken string) (*websocket.Conn, context.Context, context.CancelFunc, error) {
|
||||
ctx, ctxCancel := context.WithTimeout(context.Background(), time.Second*3)
|
||||
|
||||
// Init websocket connection
|
||||
dialer := websocket.DefaultDialer
|
||||
conn, _, err := dialer.DialContext(ctx, fmt.Sprintf("ws://%s:%s/api/websocket", ip, port), nil)
|
||||
conn, _, err := dialer.DialContext(ctx, uri, nil)
|
||||
if err != nil {
|
||||
ctxCancel()
|
||||
slog.Error("Failed to connect to websocket at ws://%s:%s/api/websocket. Check IP address and port\n", ip, port)
|
||||
slog.Error("Failed to connect to websocket. Check URI\n", "uri", uri)
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user