This repository has been archived by the owner on Nov 19, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
95 lines (80 loc) · 2.33 KB
/
client.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
package uaac
import (
"crypto/tls"
"fmt"
"io"
"io/ioutil"
"net/http"
"sync"
)
var _client *http.Client
var mutex sync.Mutex
// Http Client, wraps go's http.Client for our usecase
type Client struct {
Host string
BasicAuthUsername string
BasicAuthPassword string
AccessToken string
VerifySSL bool
}
func NewClient(host string, verifySSL bool) Client {
return Client{
Host: host,
VerifySSL: verifySSL,
}
}
func (client Client) WithBasicAuthCredentials(clientID, clientSecret string) Client {
client.BasicAuthUsername = clientID
client.BasicAuthPassword = clientSecret
client.AccessToken = ""
return client
}
func (client Client) WithAuthorizationToken(token string) Client {
client.BasicAuthUsername = ""
client.BasicAuthPassword = ""
client.AccessToken = token
return client
}
func GetClient(client Client) *http.Client {
mutex.Lock()
defer mutex.Unlock()
if _client == nil {
_client = &http.Client{
Transport: &http.Transport{
TLSClientConfig: client.TLSConfig(),
},
}
}
return _client
}
// Make request with the given basic auth and ssl settings, returns reponse code and body as a byte array
func (client Client) MakeRequest(method, path string, requestBody io.Reader) (int, []byte, error) {
url := client.Host + path
request, err := http.NewRequest(method, url, requestBody)
if err != nil {
return 0, nil, err
}
if client.BasicAuthUsername != "" {
request.SetBasicAuth(client.BasicAuthUsername, client.BasicAuthPassword)
} else {
request.Header.Set("Authorization", "Bearer "+client.AccessToken)
}
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
fmt.Printf("\nConnecting to UAA with Request: %#v\n", request)
httpClient := GetClient(client)
response, err := httpClient.Do(request)
if err != nil {
return 0, nil, err
}
fmt.Printf("\nGot UAA Response: %#v\n", response)
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return response.StatusCode, body, err
}
return response.StatusCode, body, nil
}
func (client Client) TLSConfig() *tls.Config {
return &tls.Config{
InsecureSkipVerify: !client.VerifySSL,
}
}