This repository has been archived by the owner on Jan 2, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathclient.go
179 lines (150 loc) · 5.12 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
package starling
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"strings"
"github.com/pkg/errors"
)
const (
// ProdURL for the production instance of the Starling API
ProdURL = "https://api.starlingbank.com/"
// SandboxURL for the sandbox instance of the Starling API
SandboxURL = "https://api-sandbox.starlingbank.com/"
// defaultURL sets the default to using the sandbox API
defaultURL = SandboxURL
userAgent = "go-starling"
)
// ClientOptions is a set of options that can be specified when creating a Starling client
type ClientOptions struct {
BaseURL *url.URL
}
// Client holds configuration items for the Starling client and provides methods
// that interact with the Starling API.
type Client struct {
baseURL *url.URL
userAgent string
client *http.Client
}
// NewClient returns a new Starling API client. If a nil httpClient is
// provided, http.DefaultClient will be used. To use API methods which require
// authentication, provide an http.Client that will perform the authentication
// for you (such as that provided by the golang.org/x/oauth2 library).
// Inspiration: https://github.com/google/go-github/blob/master/github/github.go
func NewClient(cc *http.Client) *Client {
if cc == nil {
cc = http.DefaultClient
}
baseURL, _ := url.Parse(defaultURL)
c := &Client{baseURL: baseURL, userAgent: userAgent, client: cc}
return c
}
// NewClientWithOptions takes ClientOptions, configures and returns a new client.
func NewClientWithOptions(cc *http.Client, opts ClientOptions) *Client {
c := NewClient(cc)
c.baseURL = opts.BaseURL
return c
}
// NewRequest creates an HTTP Request. The client baseURL is checked to confirm that it has a trailing
// slash. A relative URL should be provided without the leading slash. If a non-nil body is provided
// it will be JSON encoded and included in the request.
// Inspiration: https://github.com/google/go-github/blob/master/github/github.go
func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error) {
if strings.HasSuffix(c.baseURL.Path, "/") == false {
return nil, fmt.Errorf("client baseURL does not have a trailing slash: %q", c.baseURL)
}
u, err := c.baseURL.Parse(urlStr)
if err != nil {
return nil, err
}
var buf io.ReadWriter
if body != nil {
buf = new(bytes.Buffer)
enc := json.NewEncoder(buf)
enc.SetEscapeHTML(false)
err := enc.Encode(body)
if err != nil {
return nil, err
}
}
req, err := http.NewRequest(method, u.String(), buf)
if err != nil {
return nil, err
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
req.Header.Set("Accept", "application/json")
if c.userAgent != "" {
req.Header.Set("User-Agent", c.userAgent)
}
return req, nil
}
// Do sends a request and returns the response. An error is returned if the request cannot
// be sent or if the API returns an error. If a response is received, the body response body
// is decoded and stored in the value pointed to by v.
// Inspiration: https://github.com/google/go-github/blob/master/github/github.go
func (c *Client) Do(ctx context.Context, req *http.Request, v interface{}) (*http.Response, error) {
req = req.WithContext(ctx)
resp, err := c.client.Do(req)
if err != nil {
select {
case <-ctx.Done():
return nil, errors.Wrap(err, ctx.Err().Error())
default:
return nil, err
}
}
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, errors.Wrap(err, "unable to read body")
}
resp.Body.Close()
// Anything other than a HTTP 2xx response code is treated as an error. But the structure of error
// responses differs depending on the API being called. Some APIs return validation errors as part
// of the standard response. Others respond with a standardised error structure.
if c := resp.StatusCode; c >= 300 {
// Handle auth errors
if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden {
err := AuthError(http.StatusText(resp.StatusCode))
return resp, err
}
// Try parsing the response using the standard error schema. If this fails we wrap the parsing
// error and return. Otherwise return the errors included in the API response payload.
var e = Errors{}
err := json.Unmarshal(data, &e)
if err != nil {
err = errors.Wrap(err, http.StatusText(resp.StatusCode))
return resp, errors.Wrap(err, "unable to parse API error response")
}
if len(e) != 0 {
return resp, errors.Wrap(e, http.StatusText(resp.StatusCode))
}
// In some cases, the error response is returned as part of the
// requested resource. In these cases we attempt to decode the
// resource and return the error.
err = json.Unmarshal(data, v)
if err != nil {
err = errors.Wrap(err, http.StatusText(resp.StatusCode))
return resp, errors.Wrap(err, "unable to parse API response")
}
err = errors.New("no additional error information available")
return resp, errors.Wrap(err, http.StatusText(resp.StatusCode))
}
if v != nil && len(data) != 0 {
err = json.Unmarshal(data, v)
switch err {
case nil:
case io.EOF:
err = nil
default:
err = errors.Wrap(err, "unable to parse API response")
}
}
return resp, err
}