/
gateway.go
187 lines (169 loc) · 4.6 KB
/
gateway.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
package feather
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"reflect"
"strings"
)
const (
contentType string = "application/x-www-form-urlencoded"
defaultProtocol string = "https"
defaultHost string = "api.feather.id"
defaultPort string = "443"
defaultBasePath string = "/v1"
)
type gateway struct {
apiKey string
config Config
client *http.Client
}
func (g gateway) sendRequest(method string, path string, data interface{}, writeTo interface{}) error {
req, err := g.buildRequest(method, path, data)
if err != nil {
return Error{
Type: ErrorTypeValidation,
Message: fmt.Sprintf("The HTTP request failed to build because of the following error: %v", err.Error()),
}
}
resp, err := g.getClient().Do(req)
if err != nil {
return Error{
Type: ErrorTypeAPIConnection,
Message: fmt.Sprintf("A connection to the Feather API could not be established because of the following error: %v", err.Error()),
}
}
return parseResponse(resp, writeTo)
}
func (g gateway) buildRequest(method string, path string, data interface{}) (*http.Request, error) {
url := buildRequestURL(method, path, data, g.config)
var body io.Reader
if method == http.MethodPost {
body = buildRequestBody(data)
}
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, err
}
req.SetBasicAuth(g.apiKey, "")
req.Header.Set("Content-Type", contentType)
return req, nil
}
func (g gateway) getClient() *http.Client {
if g.config.HTTPClient != nil {
return g.config.HTTPClient
}
return http.DefaultClient
}
func buildRequestURL(method string, path string, data interface{}, cfg Config) string {
protocol := defaultProtocol
if cfg.Protocol != nil {
protocol = *cfg.Protocol
}
host := defaultHost
if cfg.Host != nil {
host = *cfg.Host
}
port := defaultPort
if cfg.Port != nil {
port = *cfg.Port
}
basePath := defaultBasePath
if cfg.BasePath != nil {
basePath = *cfg.BasePath
}
query := ""
if method == http.MethodGet {
query = "?" + urlEncodeData(data)
}
return fmt.Sprintf("%v://%v:%v%v%v%v", protocol, host, port, basePath, path, query)
}
func buildRequestBody(data interface{}) io.Reader {
encData := urlEncodeData(data)
var body io.Reader
if encData != "" {
body = strings.NewReader(encData)
}
return body
}
func urlEncodeData(data interface{}) string {
if data == nil {
return ""
}
// Joins two strings of url-encoded data together
joinEncData := func(a string, b string) string {
if a == "" {
return b
} else if b == "" {
return a
}
return a + "&" + b
}
// Assumes data is a struct
// Iterate through the fields of the struct and url-encodes the field/value pairs
encData := ""
rData := reflect.ValueOf(data)
rDataType := reflect.TypeOf(data)
urlVals := url.Values{}
for i := 0; i < rData.NumField(); i++ {
// Only encode non-nil values
if rData.Field(i).Kind() != reflect.Ptr || !rData.Field(i).IsNil() {
if rData.Field(i).Kind() == reflect.Struct {
// If the value is a struct, recursively flatten the request
encData = joinEncData(encData, urlEncodeData(rData.Field(i).Interface()))
} else if tag := rDataType.Field(i).Tag.Get("json"); tag != "" {
// Otherwise, get the json tag for this value...
var rDataField = rData.Field(i)
// Dereference pointer values
if rDataField.Kind() == reflect.Ptr {
rDataField = rDataField.Elem()
}
if rDataField.Kind() == reflect.Map {
// If the value is a map, create a special key
iter := rDataField.MapRange()
for iter.Next() {
k := iter.Key().Interface()
v := iter.Value().Interface()
urlVals.Add(fmt.Sprintf("%v[%v]", tag, k), fmt.Sprintf("%v", v))
}
} else {
// Otherwise, just cast the value to a string
urlVals.Add(tag, fmt.Sprintf("%v", rDataField.Interface()))
}
}
}
}
// Encode the collected key/vale pairs
encData = joinEncData(encData, urlVals.Encode())
return encData
}
func parseResponse(resp *http.Response, into interface{}) error {
type object struct {
Object string `json:"object"`
}
unparsableResponseError := Error{
Type: ErrorTypeAPI,
Message: fmt.Sprintf("The gateway received an unparsable response with status code %v",
resp.StatusCode),
}
bytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return unparsableResponseError
}
var obj object
if err = json.Unmarshal(bytes, &obj); err != nil {
return unparsableResponseError
}
const objectError = "error"
if obj.Object == objectError {
var ferr Error
if err = json.Unmarshal(bytes, &ferr); err != nil {
return unparsableResponseError
}
return ferr
}
return json.Unmarshal(bytes, into)
}