-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
241 lines (198 loc) · 7.22 KB
/
client.go
File metadata and controls
241 lines (198 loc) · 7.22 KB
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
package enablebankinggo
import (
"bytes"
"context"
"crypto/rsa"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"time"
)
const (
// ClientDefaultAPIBaseURL is the default base URL for the Enable Banking API.
ClientDefaultAPIBaseURL = "https://api.enablebanking.com"
// ClientDefaultTokenTTL is the default token time-to-live (TTL) in seconds (1 hour).
ClientDefaultTokenTTL = 3600
// ClientMaximumTokenTTL is the maximum token time-to-live (TTL) in seconds (24 hours).
ClientMaximumTokenTTL = 86400
// ClientDefaultTokenTTLExtraTime is the extra time added to the token TTL to account for clock skew.
ClientDefaultTokenTTLExtraTime = 10 * time.Second
)
// ClientOption represents a configuration option for the client.
type ClientOption func(*APIClient)
// WithBaseURL sets a custom base URL for the Enable Banking API client.
func WithBaseURL(baseURL string) ClientOption {
return func(c *APIClient) {
c.baseURL = strings.TrimSuffix(baseURL, "/")
}
}
// WithHTTPClient sets a custom HTTP client for the Enable Banking API client.
func WithHTTPClient(httpClient *http.Client) ClientOption {
return func(c *APIClient) {
c.httpClient = httpClient
}
}
// WithHTTPTransport sets a custom HTTP transport for the client.
func WithHTTPTransport(transport http.RoundTripper) ClientOption {
return func(c *APIClient) {
c.httpClient.Transport = transport
}
}
// WithTokenTTL sets a custom token time-to-live (TTL) in seconds. Default is [ClientDefaultTokenTTL] seconds. Maximum is [ClientMaximumTokenTTL] seconds.
func WithTokenTTL(ttl int) ClientOption {
if ttl <= 0 || ttl > ClientMaximumTokenTTL {
panic("token TTL must be between 1 and 86400 seconds")
}
return func(c *APIClient) {
c.authorizer.tokenTTL = int64(ttl)
}
}
// WithTokenTTLExtraTime sets a custom extra time duration to account for clock skew when validating token expiration. Default is [ClientDefaultTokenTTLExtraTime].
func WithTokenTTLExtraTime(extraTime time.Duration) ClientOption {
return func(c *APIClient) {
c.authorizer.extraTTL = extraTime
}
}
// WithHeaders sets additional headers to include in every request made by the client.
func WithHeaders(headers Header) ClientOption {
return func(c *APIClient) {
for k, v := range headers {
c.headers.Set(k, v)
}
}
}
// WithPSUIPAddressHeader sets the [PSUIPAddressHeaderKey] header to include in every request made by the client.
func WithPSUIPAddressHeader(ipAddress string) ClientOption {
return func(c *APIClient) {
c.headers.Set(PSUIPAddressHeaderKey, ipAddress)
}
}
// WithPSUUserAgentHeader sets the [PSUUserAgentHeaderKey] header to include in every request made by the client.
func WithPSUUserAgentHeader(userAgent string) ClientOption {
return func(c *APIClient) {
c.headers.Set(PSUUserAgentHeaderKey, userAgent)
}
}
// WithPSURefererHeader sets the [PSURefererHeaderKey] header to include in every request made by the client.
func WithPSURefererHeader(referer string) ClientOption {
return func(c *APIClient) {
c.headers.Set(PSURefererHeaderKey, referer)
}
}
// WithPSUAcceptHeader sets the [PSUAcceptHeaderKey] header to include in every request made by the client.
func WithPSUAcceptHeader(accept string) ClientOption {
return func(c *APIClient) {
c.headers.Set(PSUAcceptHeaderKey, accept)
}
}
// WithPSUAcceptCharset sets the [PSUAcceptCharsetHeaderKey] header to include in every request made by the client.
func WithPSUAcceptCharset(acceptCharset string) ClientOption {
return func(c *APIClient) {
c.headers.Set(PSUAcceptCharsetHeaderKey, acceptCharset)
}
}
// WithPSUAcceptEncoding sets the [PSUAcceptEncodingHeaderKey] header to include in every request made by the client.
func WithPSUAcceptEncoding(acceptEncoding string) ClientOption {
return func(c *APIClient) {
c.headers.Set(PSUAcceptEncodingHeaderKey, acceptEncoding)
}
}
// WithPSUAcceptLanguage sets the [PSUAcceptLanguageHeaderKey] header to include in every request made by the client.
func WithPSUAcceptLanguage(acceptLanguage string) ClientOption {
return func(c *APIClient) {
c.headers.Set(PSUAcceptLanguageHeaderKey, acceptLanguage)
}
}
// WithPSUGeoLocationHeader sets the [PSUGeoLocationHeaderKey] header to include in every request made by the client.
func WithPSUGeoLocationHeader(geoLocation string) ClientOption {
return func(c *APIClient) {
c.headers.Set(PSUGeoLocationHeaderKey, geoLocation)
}
}
// NewClientWithKeyFile creates a new Enable Banking API client with the provided application ID, private key file path, and options.
// If no options are provided, the client will use default settings of [ClientDefaultAPIBaseURL], [ClientDefaultTokenTTL], and [ClientDefaultTokenTTLExtraTime].
func NewClientWithKeyFile(applicationID, privateKeyPath string, options ...ClientOption) (*APIClient, error) {
privateKey, err := loadPrivateKeyFromFile(privateKeyPath)
if err != nil {
return nil, fmt.Errorf("failed to load private key from file: %w", err)
}
return NewClient(applicationID, privateKey, options...)
}
// NewClient creates a new Enable Banking API client with the provided application ID, private key, and options.
// If no options are provided, the client will use default settings of [ClientDefaultAPIBaseURL], [ClientDefaultTokenTTL], and [ClientDefaultTokenTTLExtraTime].
func NewClient(applicationID string, privateKey *rsa.PrivateKey, options ...ClientOption) (*APIClient, error) {
if applicationID == "" {
return nil, errors.New("application ID cannot be empty")
}
if privateKey == nil {
return nil, errors.New("private key cannot be nil")
}
c := &APIClient{
baseURL: ClientDefaultAPIBaseURL,
httpClient: http.DefaultClient,
headers: NewHeaders(),
authorizer: newAuthorizer(applicationID, privateKey, ClientDefaultTokenTTL, ClientDefaultTokenTTLExtraTime),
}
c.httpClient.Timeout = 30 * time.Second
for _, option := range options {
option(c)
}
return c, nil
}
type APIClient struct {
baseURL string
httpClient *http.Client
headers Header
authorizer *authorizer
}
func (c *APIClient) newRequest(ctx context.Context, method, url string, reqBody any) (*http.Request, error) {
if !strings.HasPrefix(url, "/") {
url = "/" + url
}
var body io.Reader
if reqBody != nil {
jsonData, err := json.Marshal(reqBody)
if err != nil {
return nil, fmt.Errorf("failed to marshal request body: %w", err)
}
body = bytes.NewReader(jsonData)
}
req, err := http.NewRequestWithContext(ctx, method, c.baseURL+url, body)
if err != nil {
return nil, err
}
c.headers.FillHTTPHeader(req.Header)
if reqBody != nil {
req.Header.Set("Content-Type", "application/json")
}
err = c.authorizer.AuthorizeRequest(req)
if err != nil {
return nil, err
}
return req, nil
}
func (c *APIClient) sendRequest(req *http.Request, resp any) error {
response, err := c.httpClient.Do(req)
if err != nil {
return err
}
defer response.Body.Close()
if response.StatusCode < 200 || response.StatusCode > 500 {
return fmt.Errorf("unexpected status code: %d", response.StatusCode)
}
if response.StatusCode != 200 {
var errResp ErrorResponse
err = json.NewDecoder(response.Body).Decode(&errResp)
if err != nil {
return fmt.Errorf("unexpected API error: status code %d", response.StatusCode)
}
return &errResp
}
if resp != nil {
return json.NewDecoder(response.Body).Decode(resp)
}
return nil
}