-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
189 lines (151 loc) · 4.83 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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
package mymobileapi
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"net/http/httputil"
"strings"
"time"
)
// Client represents a client to the mymobile REST API.
type Client struct {
authorization string
authToken string
AuthTokenExpiry time.Time
debug bool
endpoint string
httpClient *http.Client
}
// NewClient returns a client.
func NewClient(clientID, clientSecret string, debug bool) (*Client, error) {
// Create Authorization header from client ID & secret
authorization := "BASIC " + base64.StdEncoding.EncodeToString([]byte(clientID+":"+clientSecret))
client := Client{authorization: authorization, endpoint: "https://rest.mymobileapi.com/v1/", debug: debug, httpClient: &http.Client{}}
err := client.Authenticate()
if err != nil {
return nil, err
}
return &client, err
}
// Authenticate to API, generating an Authentication token for use in future requests.
func (c *Client) Authenticate() error {
authResponse := struct {
Token string `json:"token"`
Schema string `json:"schema"`
ExpiresInMinutes int `json:"expiresInMinutes"`
}{}
_, err := c.get("Authentication", nil, &authResponse)
if err != nil {
return err
}
duration, err := time.ParseDuration(fmt.Sprint(authResponse.ExpiresInMinutes) + "m")
if err != nil {
return err
}
c.AuthTokenExpiry = time.Now().Add(duration)
c.authToken = "Bearer " + authResponse.Token
return nil
}
func (c *Client) ask(method, path string, params, recipient interface{}) (http.Header, error) {
resp, err := c.do(method, path, params, nil)
if err != nil {
return nil, err
}
defer resp.Body.Close()
decoder := json.NewDecoder(resp.Body)
decoder.Decode(recipient)
return resp.Header, nil
}
type StandardResponse struct {
Code int `json:"code,omitempty"`
Message string `json:"message,omitempty"`
UUID string `json:"uuid,omitempty"`
Object string `json:"object,omitempty"`
Cause string `json:"cause,omitempty"`
Status string `json:"status,omitempty"`
Errors []StandardError `json:"errors,omitempty"`
}
type StandardError struct {
Location string `json:"location"`
Name string `json:"name"`
Description string `json:"description"`
}
func (c *Client) do(method, path string, p interface{}, extraHeaders [][2]string) (*http.Response, error) {
var (
err error
req *http.Request
)
params, err := json.Marshal(p)
if err != nil {
return nil, err
}
suffix := ""
if params != nil && string(params) != "null" {
req, err = http.NewRequest(method, c.endpoint+path+suffix, bytes.NewReader(params))
} else {
req, err = http.NewRequest(method, c.endpoint+path+suffix, nil)
}
if err != nil {
return nil, err
}
// If authentication token is empty, use client ID & secret for authentication.
// This is only valid for the Authentication endpoint.
if c.authToken == "" {
req.Header.Add("Authorization", c.authorization)
} else {
req.Header.Add("Authorization", c.authToken)
}
req.Header.Add("Content-Type", "application/json")
for _, header := range extraHeaders {
req.Header.Add(header[0], header[1])
}
if c.debug {
dump, _ := httputil.DumpRequestOut(req, true)
fmt.Println("=======================================\nREQUEST:")
fmt.Println(string(dump))
}
resp, err := c.httpClient.Do(req)
if err != nil {
return resp, err
}
if c.debug {
dump, _ := httputil.DumpResponse(resp, true)
fmt.Println("=======================================\nRESPONSE:")
fmt.Println(string(dump))
}
if resp.StatusCode < 200 || resp.StatusCode > 299 {
defer resp.Body.Close()
var message StandardResponse
decoder := json.NewDecoder(resp.Body)
decoder.Decode(&message)
if message.Message != "" {
err = fmt.Errorf("%d: %s", resp.StatusCode, message.Message)
} else if len(message.Errors) > 0 {
var errors []string
for _, oneError := range message.Errors {
errors = append(errors, fmt.Sprintf("%s: %s", oneError.Name, oneError.Description))
}
err = fmt.Errorf(strings.Join(errors, ", "))
} else {
err = fmt.Errorf("%d", resp.StatusCode)
}
}
return resp, err
}
func (c *Client) get(path string, params, recipient interface{}) (http.Header, error) {
return c.ask(http.MethodGet, path, params, recipient)
}
func (c *Client) post(path string, params, recipient interface{}) (http.Header, error) {
return c.ask(http.MethodPost, path, params, recipient)
}
func (c *Client) put(path string, params, recipient interface{}) (http.Header, error) {
return c.ask(http.MethodPut, path, params, recipient)
}
func (c *Client) patch(path string, params, recipient interface{}) (http.Header, error) {
return c.ask(http.MethodPatch, path, params, recipient)
}
func (c *Client) delete(path string, params, recipient interface{}) (http.Header, error) {
return c.ask(http.MethodDelete, path, params, recipient)
}