-
Notifications
You must be signed in to change notification settings - Fork 6
/
client.go
180 lines (149 loc) · 3.8 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
180
// Copyright 2021-present Airheart, Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
package duffel
import (
"bytes"
"compress/gzip"
"context"
"fmt"
"io"
"net/http"
"net/http/httputil"
"net/url"
"strings"
"github.com/segmentio/encoding/json"
)
const RequestIDHeader = "x-request-id"
type Payload[T any] struct {
Data T `json:"data"`
}
type ResponsePayload[T any] struct {
Meta *ListMeta `json:"meta"`
Data T `json:"data"`
}
type RequestOption func(req *http.Request) error
type EmptyPayload struct{}
func buildRequestPayload[T any](data T) *Payload[T] {
return &Payload[T]{
Data: data,
}
}
func encodePayload[T any](requestInput T) (io.ReadCloser, error) {
payload := bytes.NewBuffer(nil)
err := json.NewEncoder(payload).Encode(buildRequestPayload(requestInput))
if err != nil {
return nil, err
}
return io.NopCloser(payload), nil
}
func (c *client[R, T]) makeRequest(ctx context.Context, resourceName string, method string, body io.ReadCloser, opts ...RequestOption) (*http.Response, error) {
if c.APIToken == "" {
return nil, fmt.Errorf("duffel: missing API token")
}
u, err := c.buildRequestURL(resourceName)
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, method, u.String(), nil)
if err != nil {
return nil, err
}
if method != http.MethodGet {
req.Body = body
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Accept", "application/json")
if !c.options.Debug {
req.Header.Add("Accept-Encoding", "gzip")
}
req.Header.Add("User-Agent", c.options.UserAgent)
req.Header.Add("Duffel-Version", c.options.Version)
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", c.APIToken))
// Apply request options
for _, o := range opts {
if o != nil {
err := o(req)
if err != nil {
return nil, err
}
}
}
if c.options.Debug {
b, err := httputil.DumpRequestOut(req, true)
if err != nil {
return nil, err
}
fmt.Printf("REQUEST:\n%s\n", string(b))
}
resp, err := c.httpDoer.Do(req)
if err != nil {
return nil, err
}
if c.options.Debug {
b, err := httputil.DumpResponse(resp, true)
if err != nil {
return nil, err
}
fmt.Printf("RESPONSE:\n%s\n", string(b))
}
if resp.StatusCode > 399 {
err = decodeError(resp)
return nil, err
}
return resp, nil
}
func (c *client[R, T]) buildRequestURL(resourceName string) (*url.URL, error) {
u, err := url.Parse(c.options.Host)
if err != nil {
return nil, err
}
u.Path = resourceName
return u, nil
}
func gzipResponseReader(response *http.Response) (io.ReadCloser, error) {
var reader io.ReadCloser
var err error
if response.Header.Get("Content-Encoding") == "gzip" {
reader, err = gzip.NewReader(response.Body)
if err != nil {
return nil, err
}
} else {
reader = response.Body
}
return reader, nil
}
func decodeError(response *http.Response) error {
reader, err := gzipResponseReader(response)
if err != nil {
return err
}
contentType := response.Header.Get("Content-Type")
if strings.HasPrefix(contentType, "text/html") {
// Handle occasional HTML error pages at routing layer
return &DuffelError{
StatusCode: response.StatusCode,
Retryable: true,
Errors: []Error{
{
Type: ErrorType(InternalServerError),
Title: http.StatusText(response.StatusCode),
Message: "An internal server error occurred. Please try again later.",
Code: InternalServerError,
},
},
}
}
notRetryable := strings.HasPrefix(response.Request.URL.Path, "/air/orders") &&
response.StatusCode == http.StatusInternalServerError
derr := &DuffelError{
StatusCode: response.StatusCode,
Retryable: !notRetryable,
}
err = json.NewDecoder(reader).Decode(derr)
if err != nil {
return err
}
return derr
}