-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
66 lines (50 loc) · 1.32 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
package enswitch
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
)
type Client struct {
httpClient *http.Client
username, password, baseURL string
Customer *Customers
}
func (c *Client) newRequest(ctx context.Context, uri string, qs url.Values) (*http.Request, error) {
if ctx == nil {
return nil, ErrContextNil
}
u, err := url.Parse(c.baseURL)
if err != nil {
return nil, ErrBadURL
}
u.Path += uri
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
if err != nil {
return nil, ErrRequestWithContext
}
req.Header.Add("Content-Type", "Application/JSON")
req.Header.Add("User-Agent", "Enswitch-GO")
req.URL.RawQuery = c.parseQueryParams(qs).Encode()
return req, nil
}
func (c *Client) call(req *http.Request, v interface{}) (*http.Response, error) {
res, err := c.httpClient.Do(req)
if err != nil {
return nil, ErrHTTPRequest
}
if res.StatusCode != http.StatusOK {
return nil, fmt.Errorf("server responded with error code: %w: %d", ErrHTTPRequest, res.StatusCode)
}
err = json.NewDecoder(res.Body).Decode(v)
if err != nil {
return nil, ErrDecodingRequest
}
return res, nil
}
func (c *Client) parseQueryParams(qs url.Values) url.Values {
qs.Add("auth_username", c.username)
qs.Add("auth_password", c.password)
return qs
}