-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
85 lines (71 loc) · 1.9 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
package gocardless
import (
"context"
"fmt"
"os"
"os/signal"
"syscall"
"time"
)
// Client is the Nordigen client
type Client struct {
HTTP IHTTPClient
SecretID string
SecretKey string
Token *Token
}
type Config struct {
BaseURL string
APIVersion string
SecretID string `json:"secret_id"`
SecretKey string `json:"secret_key"`
TokenRefresh bool
HTTP *Client
}
// New creates a new Gocardless client
func New(config *Config) (*Client, error) {
client := &Client{
HTTP: NewHTTPClient(config.BaseURL, config.APIVersion),
SecretID: config.SecretID,
SecretKey: config.SecretKey,
}
token, err := client.NewToken(context.Background())
if err != nil {
return nil, fmt.Errorf("failed to get token: %w", err)
}
client.Token = token
if config.TokenRefresh {
go refreshGocardlessToken(client)
}
return client, nil
}
// refreshGocardlessToken refreshes the access token and the refresh token
func refreshGocardlessToken(client *Client) {
sigterm := make(chan os.Signal, 1)
signal.Notify(sigterm, syscall.SIGTERM, syscall.SIGINT)
for {
select {
case <-sigterm:
fmt.Println("Received termination signal, exiting refreshGocardlessToken")
return
case <-time.After(1 * time.Minute):
if time.Unix(int64(client.Token.AccessExpires), 0).Before(time.Now().Add(1 * time.Minute)) {
newToken, err := client.RefreshToken(context.Background(), client.Token.Refresh)
if err != nil {
fmt.Printf("failed to refresh access token: %v\n", err)
continue
}
client.Token.Access = newToken.Access
client.Token.AccessExpires = newToken.AccessExpires
}
if time.Unix(int64(client.Token.RefreshExpires), 0).Before(time.Now().Add(1 * time.Minute)) {
newToken, err := client.NewToken(context.Background())
if err != nil {
fmt.Printf("failed to create new token: %v\n", err)
continue
}
client.Token = newToken
}
}
}
}