-
Notifications
You must be signed in to change notification settings - Fork 3
/
lob.go
267 lines (235 loc) · 6.39 KB
/
lob.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
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
package lob
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"reflect"
"runtime"
"strconv"
"strings"
"github.com/op/go-logging"
)
var log = logging.MustGetLogger("lob")
// LogStackTrace logs a stack trace for the given error.
func logStackTrace(err error) {
buf := make([]byte, 0, 16384)
n := runtime.Stack(buf, false)
if err != nil {
log.Errorf("Non-nil error %s; stack trace %s", err.Error(), buf[:n])
} else {
log.Errorf("Nil error; stack trace %s", buf[:n])
}
}
type Lob interface {
// Checks
CreateCheck(*CreateCheckRequest) (*Check, error)
GetCheck(string) (*Check, error)
CancelCheck(string) (*CancelCheckResponse, error)
ListChecks(int) (*ListChecksResponse, error)
// Addresses
CreateAddress(*Address) (*Address, error)
GetAddress(string) (*Address, error)
DeleteAddress(string) error
ListAddresses(int) (*ListAddressesResponse, error)
VerifyUSAddress(*Address) (*USAddressVerificationResponse, error)
// NamedObject
GetStates() (*NamedObjectList, error)
GetCountries() (*NamedObjectList, error)
// Bank Accounts
CreateBankAccount(*CreateBankAccountRequest) (*BankAccount, error)
GetBankAccount(string) (*BankAccount, error)
ListBankAccounts(int) (*ListBankAccountsResponse, error)
}
// Lob represents information on how to connect to the lob.com API.
type lob struct {
BaseAPI string
APIKey string
UserAgent string
}
// Base URL and API version for Lob.
const (
BaseAPI = "https://api.lob.com/v1/"
APIVersion = "2019-06-01"
)
// NewLob creates an object that can be used to connect to the lob.com API.
func NewLob(baseAPI, apiKey, userAgent string) *lob {
return &lob{
BaseAPI: baseAPI,
APIKey: apiKey,
UserAgent: userAgent,
}
}
func queryParams(params map[string]string) string {
if params == nil {
return ""
}
pieces := make([]string, 0, len(params))
for k, v := range params {
pieces = append(pieces, fmt.Sprintf("%s=%s", url.QueryEscape(k), url.QueryEscape(v)))
}
return "?" + strings.Join(pieces, "&")
}
// Use JSON tag information to create a form values map.
func json2form(v interface{}) map[string]string {
value := reflect.ValueOf(v)
t := value.Type()
params := make(map[string]string)
for i := 0; i < value.NumField(); i++ {
f := t.Field(i)
name := f.Tag.Get("json")
fv := value.Field(i).Interface()
if fv == nil {
continue
}
switch x := fv.(type) {
case *string:
if x != nil {
params[name] = *x
}
case string:
if x != "" {
params[name] = x
}
case int:
if x != 0 {
params[name] = strconv.Itoa(x)
}
case *bool:
if x != nil {
params[name] = fmt.Sprintf("%v", *x)
}
case int64:
if x != 0 {
params[name] = strconv.FormatInt(x, 10)
}
case float64:
params[name] = fmt.Sprintf("%.2f", x)
case []string:
if len(x) > 0 {
params[name] = strings.Join(x, " ")
}
case map[string]string:
for mapkey, mapvalue := range x {
params[name+"["+mapkey+"]"] = mapvalue
}
case *Error:
// do not turn into form values. This is for the return response only
default:
// ignore
panic(fmt.Errorf("Unknown field type: " + value.Field(i).Type().String()))
}
}
return params
}
// Get performs a GET request to the lob API.
func (l *lob) get(endpoint string, params map[string]string, returnValue interface{}) error {
fullURL := l.BaseAPI + endpoint + queryParams(params)
log.Debugf("Lob GET %s", fullURL)
req, err := http.NewRequest("GET", fullURL, nil)
if err != nil {
logStackTrace(err)
return err
}
req.SetBasicAuth(l.APIKey, "")
req.Header.Add("Lob-Version", APIVersion)
req.Header.Add("Accept", "application/json")
req.Header.Add("User-Agent", l.UserAgent)
resp, err := http.DefaultClient.Do(req)
if err != nil {
logStackTrace(err)
return err
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
logStackTrace(err)
return err
}
if resp.StatusCode != 200 {
err = fmt.Errorf("Non-200 status code %d returned from %s with body %s", resp.StatusCode, fullURL, data)
logStackTrace(err)
json.Unmarshal(data, returnValue) // try, anyway -- in case the caller wants error info
return err
}
return json.Unmarshal(data, returnValue)
}
// Post performs a POST request to the Lob API.
func (l *lob) post(endpoint string, params map[string]string, returnValue interface{}) error {
fullURL := l.BaseAPI + endpoint
log.Debugf("Lob POST %s", fullURL)
var body io.Reader
if params != nil {
form := url.Values(make(map[string][]string))
for k, v := range params {
form.Add(k, v)
}
bodyString := form.Encode()
body = bytes.NewBuffer([]byte(bodyString))
}
req, err := http.NewRequest("POST", fullURL, body)
if err != nil {
logStackTrace(err)
return err
}
if body != nil {
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
}
req.SetBasicAuth(l.APIKey, "")
req.Header.Add("Lob-Version", APIVersion)
req.Header.Add("Accept", "application/json")
req.Header.Add("User-Agent", l.UserAgent)
resp, err := http.DefaultClient.Do(req)
if err != nil {
logStackTrace(err)
return err
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
logStackTrace(err)
return err
}
if resp.StatusCode != 200 {
err = fmt.Errorf("Non-200 status code %d returned from %s with body %s", resp.StatusCode, fullURL, data)
logStackTrace(err)
json.Unmarshal(data, returnValue) // try, anyway -- in case the caller wants error info
return err
}
return json.Unmarshal(data, returnValue)
}
// Delete performs a DELETE request to the Lob API.
func (l *lob) delete(endpoint string, returnValue interface{}) error {
fullURL := l.BaseAPI + endpoint
log.Debugf("Lob DELETE %s", fullURL)
req, err := http.NewRequest("DELETE", fullURL, nil)
if err != nil {
logStackTrace(err)
return err
}
req.SetBasicAuth(l.APIKey, "")
req.Header.Add("Lob-Version", APIVersion)
req.Header.Add("Accept", "application/json")
req.Header.Add("User-Agent", l.UserAgent)
resp, err := http.DefaultClient.Do(req)
if err != nil {
logStackTrace(err)
return err
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
logStackTrace(err)
return err
}
if resp.StatusCode != 200 {
err = fmt.Errorf("Non-200 status code %d returned from %s with body %s", resp.StatusCode, fullURL, data)
logStackTrace(err)
json.Unmarshal(data, returnValue) // try, anyway -- in case the caller wants error info
return err
}
return json.Unmarshal(data, returnValue)
}