-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathclient.go
105 lines (85 loc) · 2.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
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
package nordigen
import (
"context"
"errors"
"fmt"
"net/http"
"strings"
"sync"
"time"
)
const baseUrl = "bankaccountdata.gocardless.com"
const apiPath = "/api/v2"
type Client struct {
c *http.Client
secretId string
secretKey string
m *sync.RWMutex
token *Token
}
type Transport struct {
rt http.RoundTripper
cli *Client
}
// StartTokenHandler handles token refreshes in the background
func (c *Client) StartTokenHandler(ctx context.Context) error {
// Initialize the first token
err := c.newToken(ctx)
if err != nil {
return errors.New("getting initial token: " + err.Error())
}
go c.tokenHandler(ctx)
return nil
}
// tokenHandler gets a new token using the refresh token and a new pair when the
// refresh token expires
func (c *Client) tokenHandler(ctx context.Context) {
refresh := time.NewTicker(time.Hour * 12) // 12 hours
new := time.NewTicker(time.Hour * 24 * 14) // 14 days
defer refresh.Stop()
defer new.Stop()
for {
select {
case <-ctx.Done():
return
case <-new.C:
if err := c.newToken(ctx); err != nil {
// TODO(Martin): Improve error handling
panic(fmt.Sprintf("getting new token: %s", err))
}
case <-refresh.C:
if err := c.refreshToken(ctx); err != nil {
panic(fmt.Sprintf("refreshing token: %s", err))
}
}
}
}
func (t Transport) RoundTrip(req *http.Request) (*http.Response, error) {
req.URL.Scheme = "https"
req.URL.Host = baseUrl
req.URL.Path = strings.Join([]string{apiPath, req.URL.Path}, "/")
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Accept", "application/json")
// Add the access token to the request if it exists
if t.cli.token != nil {
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", t.cli.token.Access))
}
return t.rt.RoundTrip(req)
}
// NewClient creates a new Nordigen client that handles token refreshes and adds
// the necessary headers, host, and path to all requests.
func NewClient(secretId, secretKey string) (*Client, error) {
c := &Client{
c: &http.Client{Timeout: 60 * time.Second},
secretId: secretId,
secretKey: secretKey,
m: &sync.RWMutex{},
}
// Add transport to handle headers, host and path for all requests
c.c.Transport = Transport{rt: http.DefaultTransport, cli: c}
// Start token handler
if err := c.StartTokenHandler(context.Background()); err != nil {
return nil, err
}
return c, nil
}