This repository has been archived by the owner on Jun 29, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
101 lines (86 loc) · 2.51 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
package tuneuptechnology
import (
"bytes"
"encoding/json"
"io/ioutil"
"log"
"net/http"
"strings"
"time"
)
type Client struct {
// APIEmail is the email of the user and is required on every request
APIEmail string
// APIKey is the API key of the user and is required on every request
APIKey string
// BaseURL is the base url where the API resides
BaseURL string
// Timeout is the timeout of each request made to the API
Timeout int
// Version is the version of this client library
Version string
// Client is an HTTP client used to make API requests
Client *http.Client
}
// Version is the client library version
const Version = "3.0.1"
// Timeout is the number of seconds before a request will timeout
const Timeout = 10
// UserAgent sets the user-agent for requests
const UserAgent = "TuneupTechnologyApp/GoClient/" + Version
// baseURL sets the base url of a request, if not specified, a default will be used
func (client *Client) baseURL() string {
if client.BaseURL != "" {
return client.BaseURL
}
return "https://app.tuneuptechnology.com/api"
}
func (client *Client) httpClient() *http.Client {
if client.Client != nil {
return client.Client
}
return &http.Client{
Timeout: time.Second * time.Duration(client.Timeout),
}
}
// New returns a new Client with the given API email and key
func New(apiEmail string, apiKey string) *Client {
if apiEmail == "" || apiKey == "" {
log.Fatal("apiEmail and apiKey are required to create a Client.")
}
return &Client{
APIEmail: apiEmail,
APIKey: apiKey,
}
}
// makeHTTPRequest requests a response from the API with supplied data
func (client *Client) makeHTTPRequest(method string, endpoint string, data interface{}) map[string]interface{} {
// Based on https://christiangiacomi.com/posts/simple-put-patch-request-go/
jsonData, err := json.Marshal(data)
if err != nil {
log.Fatal(err)
}
request, err := http.NewRequest(strings.ToUpper(method), endpoint, bytes.NewBuffer(jsonData))
request.Header.Set("Accept", "application/json")
request.Header.Set("User-Agent", UserAgent)
request.Header.Set("Email", client.APIEmail)
request.Header.Set("Api-Key", client.APIKey)
if err != nil {
log.Fatal(err)
}
response, err := client.httpClient().Do(request)
if err != nil {
log.Fatal(err)
}
defer response.Body.Close()
responseData, err := ioutil.ReadAll(response.Body)
if err != nil {
log.Fatal(err)
}
var responseJson map[string]interface{}
err = json.Unmarshal(responseData, &responseJson)
if err != nil {
log.Fatal(err)
}
return responseJson
}