-
Notifications
You must be signed in to change notification settings - Fork 3
/
client.go
211 lines (182 loc) · 5.96 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
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
208
209
210
211
//go:generate go run generators/paginatorgen.go
package solus
import (
"context"
"crypto/tls"
"fmt"
"net/http"
"net/url"
"time"
)
// Client a Solus API client.
type Client struct {
BaseURL *url.URL
UserAgent string
Credentials Credentials
Headers http.Header
HTTPClient *http.Client
Logger Logger
Retries int
RetryAfter time.Duration
s service
Account *AccountService
ActivityLogs *ActivityLogsService
Applications *ApplicationsService
BackupNodes *BackupNodesService
Backups *BackupsService
ComputeResources *ComputeResourcesService
IPBlocks *IPBlocksService
Icons *IconsService
License *LicenseService
Locations *LocationsService
OsImageVersions *OsImageVersionsService
OsImages *OsImagesService
Permission *PermissionsService
Plans *PlansService
Projects *ProjectsService
Roles *RolesService
SSHKeys *SSHKeysService
ServersMigrations *ServersMigrationsService
Settings *SettingsService
Snapshots *SnapshotsService
Storage *StorageService
StorageTypes *StorageTypesService
Tasks *TasksService
Users *UsersService
VirtualServers *VirtualServersService
}
type service struct {
client *Client
}
// Authenticator interface for client authentication.
type Authenticator interface {
// Authenticate authenticates client and return credentials
// which should be used for making further API calls.
// The Client is fully initialized. Any endpoints which is not requires
// authentication may be called.
Authenticate(c *Client) (Credentials, error)
}
// EmailAndPasswordAuthenticator authenticate with specified email
// and password.
type EmailAndPasswordAuthenticator struct {
Email string
Password string
}
var _ Authenticator = EmailAndPasswordAuthenticator{}
// Authenticate authenticates by email and password.
func (a EmailAndPasswordAuthenticator) Authenticate(c *Client) (Credentials, error) {
resp, err := c.authLogin(context.Background(), AuthLoginRequest(a))
if err != nil {
return Credentials{}, err
}
return resp.Credentials, nil
}
// APITokenAuthenticator authenticate by provided API token.
type APITokenAuthenticator struct {
Token string
}
var _ Authenticator = APITokenAuthenticator{}
// Authenticate authenticates by API token.
func (a APITokenAuthenticator) Authenticate(*Client) (Credentials, error) {
return Credentials{
AccessToken: a.Token,
TokenType: "Bearer",
ExpiresAt: "",
}, nil
}
// ClientOption represent client initialization options.
type ClientOption func(c *Client)
// AllowInsecure allows skipping certificate verify.
func AllowInsecure() ClientOption {
return func(c *Client) {
c.HTTPClient.Transport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true} //nolint:gosec // We should give an ability to disable cert check.
}
}
// SetRetryPolicy sets number of retries and timeout between them.
func SetRetryPolicy(retries int, retryAfter time.Duration) ClientOption {
return func(c *Client) {
c.Retries = retries
c.RetryAfter = retryAfter
}
}
// WithLogger inject specific logger into client.
func WithLogger(logger Logger) ClientOption {
return func(c *Client) {
c.Logger = logger
}
}
// NewClient create and initialize Client instance.
func NewClient(
baseURL *url.URL,
a Authenticator,
opts ...ClientOption,
) (*Client, error) {
client := &Client{
BaseURL: baseURL,
UserAgent: "Go SDK client",
Headers: map[string][]string{
"Accept": {"application/json"},
"Content-Type": {"application/json"},
},
HTTPClient: &http.Client{
Timeout: time.Second * 35,
Transport: http.DefaultTransport.(*http.Transport).Clone(),
},
Logger: NullLogger{},
Retries: 5,
RetryAfter: 1 * time.Second,
}
for _, o := range opts {
o(client)
}
c, err := a.Authenticate(client)
if err != nil {
return nil, fmt.Errorf("authenticate: %w", err)
}
client.Credentials = c
client.Headers["Authorization"] = []string{client.Credentials.TokenType + " " + client.Credentials.AccessToken}
client.s.client = client
client.Account = (*AccountService)(&client.s)
client.ActivityLogs = (*ActivityLogsService)(&client.s)
client.Applications = (*ApplicationsService)(&client.s)
client.BackupNodes = (*BackupNodesService)(&client.s)
client.Backups = (*BackupsService)(&client.s)
client.ComputeResources = (*ComputeResourcesService)(&client.s)
client.IPBlocks = (*IPBlocksService)(&client.s)
client.Icons = (*IconsService)(&client.s)
client.License = (*LicenseService)(&client.s)
client.Locations = (*LocationsService)(&client.s)
client.OsImageVersions = (*OsImageVersionsService)(&client.s)
client.OsImages = (*OsImagesService)(&client.s)
client.Permission = (*PermissionsService)(&client.s)
client.Plans = (*PlansService)(&client.s)
client.Projects = (*ProjectsService)(&client.s)
client.Roles = (*RolesService)(&client.s)
client.SSHKeys = (*SSHKeysService)(&client.s)
client.ServersMigrations = (*ServersMigrationsService)(&client.s)
client.Settings = (*SettingsService)(&client.s)
client.Snapshots = (*SnapshotsService)(&client.s)
client.Storage = (*StorageService)(&client.s)
client.StorageTypes = (*StorageTypesService)(&client.s)
client.Tasks = (*TasksService)(&client.s)
client.Users = (*UsersService)(&client.s)
client.VirtualServers = (*VirtualServersService)(&client.s)
return client, nil
}
func (c *Client) authLogin(ctx context.Context, data AuthLoginRequest) (AuthLoginResponse, error) {
const path = "auth/login"
body, code, err := c.request(ctx, http.MethodPost, path, withBody(data))
if err != nil {
return AuthLoginResponse{}, err
}
if code != http.StatusOK {
return AuthLoginResponse{}, newHTTPError(http.MethodPost, path, code, body)
}
var resp struct {
Data AuthLoginResponse `json:"data"`
}
if err := unmarshal(body, &resp); err != nil {
return AuthLoginResponse{}, fmt.Errorf("unmarshal login response: %w", err)
}
return resp.Data, nil
}