-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
66 lines (52 loc) · 1.31 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 talend
import (
"fmt"
"io/ioutil"
"net/http"
"net/url"
)
const defaultRestURL string = "https://api.eu.cloud.talend.com/tmc/v2.2"
// Client contains the configuration for the API client
type Client struct {
HTTPClient *http.Client
APIKey string
Host string
Base string
Proxy string
}
// NewClient creates a new API client
func NewClient(apiKey string, proxy string) (*Client, error) {
if len(proxy) > 0 {
proxyURL, err := url.Parse(proxy)
if err != nil {
return nil, err
}
transport := &http.Transport{Proxy: http.ProxyURL(proxyURL)}
client := &http.Client{Transport: transport}
return &Client{
HTTPClient: client,
APIKey: apiKey,
Proxy: proxy,
}, nil
}
return &Client{
HTTPClient: http.DefaultClient,
APIKey: apiKey,
}, nil
}
func (c *Client) doRequest(req *http.Request) ([]byte, error) {
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.APIKey))
res, err := c.HTTPClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
if res.StatusCode == http.StatusOK || res.StatusCode == http.StatusNoContent || res.StatusCode == http.StatusCreated {
return body, err
}
return nil, fmt.Errorf("status: %d, body: %s", res.StatusCode, body)
}