forked from cloudfoundry/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
endpoints.go
97 lines (80 loc) · 2.51 KB
/
endpoints.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package api
import (
"fmt"
"github.com/cloudfoundry/cli/cf/configuration"
"github.com/cloudfoundry/cli/cf/errors"
"github.com/cloudfoundry/cli/cf/net"
"regexp"
"strings"
)
type EndpointRepository interface {
UpdateEndpoint(endpoint string) (finalEndpoint string, apiErr error)
}
type RemoteEndpointRepository struct {
config configuration.ReadWriter
gateway net.Gateway
}
type endpointResource struct {
ApiVersion string `json:"api_version"`
AuthorizationEndpoint string `json:"authorization_endpoint"`
LoggregatorEndpoint string `json:"logging_endpoint"`
}
func NewEndpointRepository(config configuration.ReadWriter, gateway net.Gateway) (repo RemoteEndpointRepository) {
repo.config = config
repo.gateway = gateway
return
}
func (repo RemoteEndpointRepository) UpdateEndpoint(endpoint string) (finalEndpoint string, apiErr error) {
defer func() {
if apiErr != nil {
repo.config.SetApiEndpoint("")
}
}()
endpointMissingScheme := !strings.HasPrefix(endpoint, "https://") && !strings.HasPrefix(endpoint, "http://")
if endpointMissingScheme {
finalEndpoint := "https://" + endpoint
apiErr := repo.attemptUpdate(finalEndpoint)
switch apiErr.(type) {
case nil:
case *errors.InvalidSSLCert:
return endpoint, apiErr
default:
finalEndpoint = "http://" + endpoint
apiErr = repo.attemptUpdate(finalEndpoint)
}
return finalEndpoint, apiErr
} else {
apiErr := repo.attemptUpdate(endpoint)
return endpoint, apiErr
}
}
func (repo RemoteEndpointRepository) attemptUpdate(endpoint string) error {
serverResponse := new(endpointResource)
err := repo.gateway.GetResource(endpoint+"/v2/info", &serverResponse)
if err != nil {
return err
}
if endpoint != repo.config.ApiEndpoint() {
repo.config.ClearSession()
}
repo.config.SetApiEndpoint(endpoint)
repo.config.SetApiVersion(serverResponse.ApiVersion)
repo.config.SetAuthenticationEndpoint(serverResponse.AuthorizationEndpoint)
if serverResponse.LoggregatorEndpoint == "" {
repo.config.SetLoggregatorEndpoint(defaultLoggregatorEndpoint(endpoint))
} else {
repo.config.SetLoggregatorEndpoint(serverResponse.LoggregatorEndpoint)
}
return nil
}
// FIXME: needs semantic versioning
func defaultLoggregatorEndpoint(apiEndpoint string) string {
matches := endpointDomainRegex.FindStringSubmatch(apiEndpoint)
url := fmt.Sprintf("ws%s://loggregator.%s", matches[1], matches[2])
if url[0:3] == "wss" {
return url + ":443"
} else {
return url + ":80"
}
}
var endpointDomainRegex = regexp.MustCompile(`^http(s?)://[^\.]+\.([^:]+)`)