forked from cloudscale-ch/cloudscale-go-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cloudscale.go
207 lines (174 loc) · 5.02 KB
/
cloudscale.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
package cloudscale
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
)
const (
libraryVersion = "v5.0.1"
defaultBaseURL = "https://api.cloudscale.ch/"
userAgent = "cloudscale/" + libraryVersion
mediaType = "application/json"
)
// Client manages communication with CloudScale API.
type Client struct {
// HTTP client used to communicate with the CloudScale API.
client *http.Client
// Base URL for API requests.
BaseURL *url.URL
// Authentication token
AuthToken string
// User agent for client
UserAgent string
Regions RegionService
Servers ServerService
Volumes VolumeService
Networks NetworkService
Subnets SubnetService
FloatingIPs FloatingIPsService
ServerGroups ServerGroupService
ObjectsUsers ObjectsUsersService
CustomImages CustomImageService
CustomImageImports CustomImageImportsService
LoadBalancers LoadBalancerService
LoadBalancerPools LoadBalancerPoolService
LoadBalancerPoolMembers LoadBalancerPoolMemberService
LoadBalancerListeners LoadBalancerListenerService
LoadBalancerHealthMonitors LoadBalancerHealthMonitorService
Metrics MetricsService
}
// NewClient returns a new CloudScale API client.
func NewClient(httpClient *http.Client) *Client {
if httpClient == nil {
httpClient = http.DefaultClient
}
// To allow more complicated testing we allow changing the cloudscale.ch
// URL.
defaultURL := os.Getenv("CLOUDSCALE_API_URL")
if defaultURL == "" {
defaultURL = defaultBaseURL
}
baseURL, _ := url.Parse(defaultURL)
c := &Client{client: httpClient, BaseURL: baseURL, UserAgent: userAgent}
c.Regions = RegionServiceOperations{client: c}
c.Servers = ServerServiceOperations{client: c}
c.Networks = NetworkServiceOperations{client: c}
c.Subnets = SubnetServiceOperations{client: c}
c.FloatingIPs = FloatingIPsServiceOperations{client: c}
c.Volumes = VolumeServiceOperations{client: c}
c.ServerGroups = ServerGroupServiceOperations{client: c}
c.ObjectsUsers = ObjectsUsersServiceOperations{client: c}
c.CustomImages = CustomImageServiceOperations{client: c}
c.CustomImageImports = CustomImageImportsServiceOperations{client: c}
c.LoadBalancers = GenericServiceOperations[LoadBalancer, LoadBalancerRequest, LoadBalancerRequest]{
client: c,
path: loadBalancerBasePath,
}
c.LoadBalancerPools = GenericServiceOperations[LoadBalancerPool, LoadBalancerPoolRequest, LoadBalancerPoolRequest]{
client: c,
path: loadBalancerPoolBasePath,
}
c.LoadBalancerPoolMembers = LoadBalancerPoolMemberServiceOperations{
client: c,
}
c.LoadBalancerListeners = GenericServiceOperations[LoadBalancerListener, LoadBalancerListenerRequest, LoadBalancerListenerRequest]{
client: c,
path: loadBalancerListenerBasePath,
}
c.LoadBalancerHealthMonitors = GenericServiceOperations[LoadBalancerHealthMonitor, LoadBalancerHealthMonitorRequest, LoadBalancerHealthMonitorRequest]{
client: c,
path: loadBalancerHealthMonitorBasePath,
}
c.Metrics = MetricsServiceOperations{client: c}
return c
}
func (c *Client) NewRequest(ctx context.Context, method, urlStr string, body interface{}) (*http.Request, error) {
rel, err := url.Parse(urlStr)
if err != nil {
return nil, err
}
u := c.BaseURL.ResolveReference(rel)
buf := new(bytes.Buffer)
if body != nil {
err = json.NewEncoder(buf).Encode(body)
if err != nil {
return nil, err
}
}
req, err := http.NewRequest(method, u.String(), buf)
if err != nil {
return nil, err
}
req.Header.Add("Content-Type", mediaType)
req.Header.Add("Accept", mediaType)
req.Header.Add("User-Agent", c.UserAgent)
if len(c.AuthToken) != 0 {
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", c.AuthToken))
}
return req, nil
}
func (c *Client) Do(ctx context.Context, req *http.Request, v interface{}) error {
req = req.WithContext(ctx)
resp, err := c.client.Do(req)
if err != nil {
return err
}
defer func() {
if rerr := resp.Body.Close(); err == nil {
err = rerr
}
}()
err = CheckResponse(resp)
if err != nil {
return err
}
if v != nil {
if w, ok := v.(io.Writer); ok {
_, err = io.Copy(w, resp.Body)
if err != nil {
return err
}
} else {
err = json.NewDecoder(resp.Body).Decode(v)
if err != nil {
return err
}
}
}
return err
}
func CheckResponse(r *http.Response) error {
if c := r.StatusCode; c >= 200 && c <= 299 {
return nil
}
data, err := ioutil.ReadAll(r.Body)
res := map[string]string{}
if err == nil && len(data) > 0 {
err := json.Unmarshal(data, &res)
if err != nil {
return err
}
}
return &ErrorResponse{
StatusCode: r.StatusCode,
Message: res,
}
}
type ErrorResponse struct {
StatusCode int
Message map[string]string
}
func (r *ErrorResponse) Error() string {
err := ""
for key, value := range r.Message {
err = fmt.Sprintf("%s: %s", key, value)
}
return err
}
type ListRequestModifier func(r *http.Request)