-
Notifications
You must be signed in to change notification settings - Fork 449
/
websocket_conn.go
82 lines (66 loc) · 1.67 KB
/
websocket_conn.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// Copyright 2024 Daytona Platforms Inc.
// SPDX-License-Identifier: Apache-2.0
package server
import (
"errors"
"fmt"
"net/http"
"net/url"
"os"
"regexp"
"github.com/daytonaio/daytona/cmd/daytona/config"
"github.com/gorilla/websocket"
)
func GetWebsocketConn(path string, profile *config.Profile, query *string) (*websocket.Conn, *http.Response, error) {
c, err := config.GetConfig()
if err != nil {
return nil, nil, err
}
var serverUrl string
var apiKey string
if envApiUrl, ok := os.LookupEnv("DAYTONA_SERVER_API_URL"); ok {
serverUrl = envApiUrl
apiKey = os.Getenv("DAYTONA_SERVER_API_KEY")
} else {
var activeProfile config.Profile
if profile == nil {
var err error
activeProfile, err = c.GetActiveProfile()
if err != nil {
return nil, nil, err
}
} else {
activeProfile = *profile
}
serverUrl = activeProfile.Api.Url
apiKey = activeProfile.Api.Key
}
url, err := url.JoinPath(serverUrl, path)
if err != nil {
return nil, nil, err
}
wsUrl, err := GetWebSocketUrl(url)
if err != nil {
return nil, nil, err
}
if query != nil {
wsUrl = fmt.Sprintf("%s?%s", wsUrl, *query)
}
return websocket.DefaultDialer.Dial(wsUrl, http.Header{
"Authorization": []string{fmt.Sprintf("Bearer %s", apiKey)},
})
}
func GetWebSocketUrl(apiUrl string) (string, error) {
hostRegex := regexp.MustCompile(`(https*)://(.*)`)
matches := hostRegex.FindStringSubmatch(apiUrl)
if len(matches) != 3 {
return "", errors.New("invalid API URL")
}
switch matches[1] {
case "http":
return fmt.Sprintf("ws://%s", matches[2]), nil
case "https":
return fmt.Sprintf("wss://%s", matches[2]), nil
}
return "", errors.New("invalid API URL protocol")
}