Parse URL and pass it to clients

Right now, this SDK only works with IP:Port.
I'm however running on https://home.example.com and need https or wss and an implicit port 443.

Using net/url should be the best option.
This commit is contained in:
Matthias Loibl
2025-01-17 01:45:42 +01:00
parent 066441762b
commit b5d35235f8
7 changed files with 67 additions and 71 deletions

View File

@@ -5,9 +5,9 @@ package http
import (
"errors"
"fmt"
"io"
"net/http"
"net/url"
)
type HttpClient struct {
@@ -15,24 +15,19 @@ type HttpClient struct {
token string
}
func NewHttpClient(ip, port, token string) *HttpClient {
return ClientFromUri(
fmt.Sprintf("http://%s:%s/api", ip, port),
token,
)
}
func NewHttpClient(url *url.URL, token string) *HttpClient {
// Shallow copy the URL to avoid modifying the original
u := *url
if u.Scheme == "ws" {
u.Scheme = "http"
}
if u.Scheme == "wss" {
u.Scheme = "https"
}
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,
url: u.String(),
token: token,
}
}

View File

@@ -10,10 +10,12 @@ import (
"errors"
"fmt"
"log/slog"
"net/url"
"sync"
"time"
"github.com/gorilla/websocket"
i "saml.dev/gome-assistant/internal"
)
@@ -49,25 +51,24 @@ func ReadMessage(conn *websocket.Conn, ctx context.Context) ([]byte, error) {
return msg, nil
}
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) {
func ConnectionFromUri(baseURL *url.URL, authToken string) (*websocket.Conn, context.Context, context.CancelFunc, error) {
ctx, ctxCancel := context.WithTimeout(context.Background(), time.Second*3)
// Shallow copy the URL to avoid modifying the original
urlWebsockets := *baseURL
if baseURL.Scheme == "http" {
urlWebsockets.Scheme = "ws"
}
if baseURL.Scheme == "https" {
urlWebsockets.Scheme = "wss"
}
// Init websocket connection
dialer := websocket.DefaultDialer
conn, _, err := dialer.DialContext(ctx, uri, nil)
conn, _, err := dialer.DialContext(ctx, urlWebsockets.String(), nil)
if err != nil {
ctxCancel()
slog.Error("Failed to connect to websocket. Check URI\n", "uri", uri)
slog.Error("Failed to connect to websocket. Check URI\n", "url", urlWebsockets)
return nil, nil, nil, err
}