forked from aiven/aiven-go-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
104 lines (84 loc) · 2.45 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
package aiven
import (
"bytes"
"encoding/json"
"io/ioutil"
"net/http"
)
const APIUrl = "https://api.aiven.io/v1beta/"
// Client represents the instance that does all the calls to the Aiven API.
type Client struct {
ApiKey string
Client *http.Client
Projects *ProjectsHandler
Services *ServicesHandler
Databases *DatabasesHandler
ServiceUsers *ServiceUsersHandler
Billing *BillingHandler
}
// NewMFAUserClient creates a new client based on email, one-time password and password.
func NewMFAUserClient(email, otp, password string) (*Client, error) {
tk, err := MFAUserToken(email, otp, password, nil)
if err != nil {
return nil, err
}
return NewTokenClient(tk.Token)
}
// NewUserClient creates a new client based on email and password.
func NewUserClient(email, password string) (*Client, error) {
return NewMFAUserClient(email, "", password)
}
// NewTokenClient creates a new client based on a given token.
func NewTokenClient(key string) (*Client, error) {
c := &Client{
ApiKey: key,
Client: &http.Client{},
}
c.Init()
return c, nil
}
// Init initializes the client and sets up all the handlers.
func (c *Client) Init() {
c.Projects = &ProjectsHandler{c}
c.Services = &ServicesHandler{c}
c.Databases = &DatabasesHandler{c}
c.ServiceUsers = &ServiceUsersHandler{c}
c.Billing = &BillingHandler{c, &CardsHandler{c}}
}
func (c *Client) doGetRequest(endpoint string, req interface{}) ([]byte, error) {
return c.doRequest("GET", endpoint, req)
}
func (c *Client) doPutRequest(endpoint string, req interface{}) ([]byte, error) {
return c.doRequest("PUT", endpoint, req)
}
func (c *Client) doPostRequest(endpoint string, req interface{}) ([]byte, error) {
return c.doRequest("POST", endpoint, req)
}
func (c *Client) doDeleteRequest(endpoint string, req interface{}) ([]byte, error) {
return c.doRequest("DELETE", endpoint, req)
}
func (c *Client) doRequest(method, uri string, body interface{}) ([]byte, error) {
var bts []byte
if body != nil {
var err error
bts, err = json.Marshal(body)
if err != nil {
return nil, err
}
}
req, err := http.NewRequest(method, endpoint(uri), bytes.NewBuffer(bts))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "aivenv1 "+c.ApiKey)
rsp, err := c.Client.Do(req)
if err != nil {
return nil, err
}
defer rsp.Body.Close()
return ioutil.ReadAll(rsp.Body)
}
func endpoint(uri string) string {
return APIUrl + uri
}