-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathclient.go
163 lines (143 loc) · 3.7 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
package hubspot
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/url"
"os"
"path"
"time"
)
// ClientConfig object used for client creation
type ClientConfig struct {
APIHost string
APIKey string
OAuthToken string
HTTPTimeout time.Duration
DialTimeout time.Duration
TLSTimeout time.Duration
}
// NewClientConfig constructs a ClientConfig object with the environment variables set as default
func NewClientConfig() ClientConfig {
apiHost := "https://api.hubapi.com"
var apiKey string
var oauthToken string
if os.Getenv("HUBSPOT_API_HOST") != "" {
apiHost = os.Getenv("HUBSPOT_API_HOST")
}
if os.Getenv("HUBSPOT_API_KEY") != "" {
apiKey = os.Getenv("HUBSPOT_API_KEY")
}
if os.Getenv("HUBSPOT_OAUTH_TOKEN") != "" {
oauthToken = os.Getenv("HUBSPOT_OAUTH_TOKEN")
}
return ClientConfig{
APIHost: apiHost,
APIKey: apiKey,
OAuthToken: oauthToken,
HTTPTimeout: 10 * time.Second,
DialTimeout: 5 * time.Second,
TLSTimeout: 5 * time.Second,
}
}
// Client object
type Client struct {
config ClientConfig
}
// NewClient constructor
func NewClient(config ClientConfig) Client {
return Client{
config: config,
}
}
// addAPIKey adds HUBSPOT_API_KEY param to a given URL.
func (c Client) addAPIKey(u string) (string, error) {
if c.config.APIKey != "" {
uri, err := url.Parse(u)
if err != nil {
return u, err
}
q := uri.Query()
q.Set("hapikey", c.config.APIKey)
uri.RawQuery = q.Encode()
u = uri.String()
}
return u, nil
}
// Request executes any HubSpot API method using the current client configuration
func (c Client) Request(method, endpoint string, data, response interface{}) error {
// Construct endpoint URL
u, err := url.Parse(c.config.APIHost)
if err != nil {
return fmt.Errorf("hubspot.Client.Request(): url.Parse(): %v", err)
}
u.Path = path.Join(u.Path, endpoint)
// API Key authentication
uri := u.String()
if c.config.APIKey != "" {
uri, err = c.addAPIKey(uri)
if err != nil {
return fmt.Errorf("hubspot.Client.Request(): c.addAPIKey(): %v", err)
}
}
// Init request object
var req *http.Request
// Send data?
if data != nil {
// Encode data to JSON
dataEncoded, err := json.Marshal(data)
if err != nil {
return fmt.Errorf("hubspot.Client.Request(): json.Marshal(): %v", err)
}
buf := bytes.NewBuffer(dataEncoded)
// Create request
req, err = http.NewRequest(method, uri, buf)
} else {
// Create no-data request
req, err = http.NewRequest(method, uri, nil)
}
if err != nil {
return fmt.Errorf("hubspot.Client.Request(): http.NewRequest(): %v", err)
}
// OAuth authentication
if c.config.APIKey == "" && c.config.OAuthToken != "" {
req.Header.Add("Authorization", "Bearer "+c.config.OAuthToken)
}
// Headers
req.Header.Add("Content-Type", "application/json")
// Execute and read response body
netClient := &http.Client{
Timeout: c.config.HTTPTimeout,
Transport: &http.Transport{
Dial: (&net.Dialer{
Timeout: c.config.DialTimeout,
}).Dial,
TLSHandshakeTimeout: c.config.TLSTimeout,
},
}
resp, err := netClient.Do(req)
if err != nil {
return fmt.Errorf("hubspot.Client.Request(): c.config.HTTPClient.Do(): %v", err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("hubspot.Client.Request(): ioutil.ReadAll(): %v", err)
}
// Get data?
if response != nil {
err = json.Unmarshal(body, &response)
if err != nil {
return fmt.Errorf("hubspot.Client.Request(): json.Unmarshal(): %v \n%s", err, string(body))
}
}
// Return HTTP errors
if resp.StatusCode != 200 && resp.StatusCode != 204 {
return fmt.Errorf("HubSpot API error: %d - %s \n%s", resp.StatusCode, resp.Status, string(body))
}
// Done!
return nil
}