-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
70 lines (59 loc) · 1.35 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
package main
import (
"fmt"
"net/http"
"os"
"time"
)
var client *MonzoClient
type MonzoClient struct {
clientID string
clientSecret string
accessToken string
refreshToken string
callbackCode string
endpoints map[string]string
httpClient *http.Client
}
func init() {
if client == nil {
client = NewClient()
}
client = &MonzoClient{
clientID: os.Getenv("MONZO_CLIENT_ID"),
clientSecret: os.Getenv("MONZO_CLIENT_SECRET"),
accessToken: "",
refreshToken: "",
callbackCode: "",
endpoints: map[string]string{
"AuthURL": "https://auth.monzo.com",
"TokenURL": "https://api.monzo.com/oauth2/token",
"APIURL": "https://api.monzo.com",
},
httpClient: &http.Client{
Timeout: time.Second * 10,
},
}
}
func NewClient() *MonzoClient {
return client
}
func (c *MonzoClient) Do(req *http.Request) (*http.Response, error) {
rsp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
// If the response status code is 401, refresh the token and retry the request
if rsp.StatusCode == http.StatusUnauthorized {
if err := refreshToken(c); err != nil {
return nil, err
}
// Update the Authorization header with the new access token.
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.accessToken))
rsp, err = c.httpClient.Do(req)
if err != nil {
return nil, err
}
}
return rsp, nil
}