-
Notifications
You must be signed in to change notification settings - Fork 14
/
restlib.go
282 lines (248 loc) · 7.94 KB
/
restlib.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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
package restlib
import (
"bytes"
"compress/gzip"
"context"
"encoding/json"
"encoding/xml"
"io"
"net/http"
"reflect"
"regexp"
"strings"
"github.com/pkg/errors"
"github.com/anz-bank/sysl-go/common"
)
// HTTPResult is the result return by the library.
type HTTPResult struct {
HTTPResponse *http.Response
Body []byte
Response interface{}
}
func (r *HTTPResult) Error() string {
return r.HTTPResponse.Status
}
func makeHTTPResult(res *http.Response, body []byte, resp interface{}) *HTTPResult {
return &HTTPResult{
HTTPResponse: res,
Body: body,
Response: resp,
}
}
func unmarshal(resp *http.Response, body []byte, respStruct interface{}) (*HTTPResult, error) {
if resp == nil {
panic("unmarshal expecting a non-nil http.Response")
}
if respStruct == nil || body == nil || len(body) == 0 {
// Obtain the respStruct's dynamic type and check if its a pointer
if p := reflect.TypeOf(respStruct); p != nil && p.Kind() == reflect.Ptr {
// Dereference the dynamic pointer type and pass the created zero value
return makeHTTPResult(resp, body, reflect.New(p.Elem()).Interface()), nil
}
return makeHTTPResult(resp, body, nil), nil
}
contentType := resp.Header.Get("Content-Type")
e := reflect.ValueOf(respStruct).Elem()
kind := e.Kind()
if kind == reflect.String || (kind == reflect.Slice && e.Type().Elem().Name() == "uint8") {
p := reflect.New(e.Type())
p.Elem().Set(reflect.ValueOf(body).Convert(e.Type()))
return makeHTTPResult(resp, body, p.Interface()), nil
}
if strings.Contains(contentType, "xml") {
respStruct = string(body)
} else {
err := json.Unmarshal(body, respStruct)
if err != nil {
return makeHTTPResult(resp, body, nil), err
}
}
return makeHTTPResult(resp, body, respStruct), nil
}
// By default, if contentType is not given or not otherwise recognised,
// the body will be encoded as JSON.
func marshalRequestBody(contentType string, v interface{}) (io.Reader, error) {
var reader io.Reader
// TODO: it would be more correct to attempt to parse the content-type value
// rather than guessing what to do based on substring matches.
switch {
case strings.Contains(contentType, "xml"):
var strBody string
strBody = reflect.ValueOf(v).Convert(reflect.TypeOf(strBody)).String()
if strings.HasSuffix(strBody, " Value>") {
return nil, errors.Errorf(`Incompatible type as xml body: %s`, strBody)
}
reader = strings.NewReader(strBody)
case strings.Contains(contentType, "application/x-www-form-urlencoded"):
reqData, err := urlencode(v)
if err != nil {
return nil, err
}
reader = bytes.NewReader(reqData)
case strings.Contains(contentType, "text/plain"), strings.Contains(contentType, "text/html"):
reqData, ok := v.(string)
if !ok {
return nil, errors.Errorf("Invalid plain text value: %v", v)
}
reader = bytes.NewReader([]byte(reqData))
case strings.Contains(contentType, "application/octet-stream"):
reqData, ok := v.([]byte)
if !ok {
return nil, errors.Errorf("Invalid byte value: %v", v)
}
reader = bytes.NewReader(reqData)
default:
// assume JSON request body.
reqJSON, err := json.Marshal(v)
if err != nil {
return nil, err
}
reader = bytes.NewReader(reqJSON)
}
return reader, nil
}
type HTTPRequest struct {
Client *http.Client
Method, URLString string
Body interface{}
Required []string
Responses func(int) any
ExtraHeaders map[string][]string
}
// DoHTTPRequest returns HTTPResult.
//
//nolint:funlen // TODO: Refactor this function to be shorter.
func DoHTTPRequest(ctx context.Context, config *HTTPRequest) (*HTTPResult, error) {
var reader io.Reader
headers := common.RequestHeaderFromContext(ctx)
contentType := headers.Get("Content-Type")
// Validations 1:
// If we have body, marshal it based on the Content-Type of the request.
if config.Body != nil {
var err error
reader, err = marshalRequestBody(contentType, config.Body)
if err != nil {
return nil, err
}
}
if config.ExtraHeaders != nil {
for key, values := range config.ExtraHeaders {
for _, v := range values {
headers.Add(key, v)
}
}
}
// Validations 2:
// if we have required headers, see if they have been passed to us
for _, key := range config.Required {
if has := headers.Get(key); has == "" {
return nil, errors.Errorf("Missing Required header: %s", key)
}
}
httpRequest, err := http.NewRequestWithContext(ctx, config.Method, config.URLString, reader)
if err != nil {
return nil, err
}
httpRequest.Header = headers
httpResponse, err := config.Client.Do(httpRequest)
if err != nil {
return nil, err
}
defer func() { _ = httpResponse.Body.Close() }()
// TODO: remove this after confirming that gzip was handled by lower layer
var bodyReader io.Reader
if m, _ := regexp.MatchString(`(?i)gzip`, httpResponse.Header.Get("Content-Encoding")); m && httpResponse.ContentLength != 0 {
bodyReader, err = gzip.NewReader(httpResponse.Body)
if err != nil {
return nil, err
}
} else {
bodyReader = httpResponse.Body
}
respBody, err := io.ReadAll(bodyReader)
if err != nil {
return nil, err
}
result, err := unmarshal(httpResponse, respBody, config.Responses(httpResponse.StatusCode))
if err != nil {
return nil, err
}
if httpResponse.StatusCode >= 200 && httpResponse.StatusCode < 300 {
return result, nil
}
// Successful unmarshal but we have unmarshalled an error.
return nil, result
}
// SendHTTPResponse sends the http response to the client.
func SendHTTPResponse(w http.ResponseWriter, httpStatus int, responses ...interface{}) {
w.WriteHeader(httpStatus)
contentType := w.Header().Get("Content-Type")
for _, resp := range responses {
if resp == nil || (reflect.ValueOf(resp).Kind() == reflect.Ptr && reflect.ValueOf(resp).IsNil()) {
continue
}
switch {
case strings.Contains(contentType, "xml"):
_ = xml.NewEncoder(w).Encode(resp)
case strings.Contains(contentType, "image"):
_, _ = w.Write(reflect.ValueOf(resp).Elem().Bytes())
case strings.Contains(contentType, "text/plain"), strings.Contains(contentType, "text/html"):
switch data := resp.(type) {
case *string:
_, _ = w.Write([]byte(*data))
case string:
_, _ = w.Write([]byte(data))
}
case strings.Contains(contentType, "octet-stream"), strings.Contains(contentType, "pdf"):
switch data := resp.(type) {
case *[]byte:
_, _ = w.Write(*data)
case []byte:
_, _ = w.Write(data)
}
default:
_ = json.NewEncoder(w).Encode(resp)
}
return
}
}
// SetHeaders sets the headers in response.
func SetHeaders(w http.ResponseWriter, headerMap http.Header) {
for k, v := range headerMap {
for _, hv := range v {
w.Header().Add(k, hv)
}
}
}
// OnRestResultHTTPResult is called from generated code when an HTTP result is retrieved.
// The current implementation of restlib.DoHTTPRequest returns an *HTTPResult as an error when a non-
// successful status code is received. The implementation of this method relies on this behaviour.
// to set the rest result in the event of a failed request.
func OnRestResultHTTPResult(ctx context.Context, result *HTTPResult, err error) {
if result != nil {
SetRestResult(ctx, toRestResult(*result))
} else if res, ok := err.(*HTTPResult); ok {
SetRestResult(ctx, toRestResult(*res))
}
}
func toRestResult(result HTTPResult) common.RestResult {
return common.RestResult{
StatusCode: result.HTTPResponse.StatusCode,
Headers: result.HTTPResponse.Header,
Body: result.Body,
}
}
// SetRestResult the contents of the common.RestResult stored in the context.
// The RestResult is stored in the context through the common.ProvisionRestResult method.
// This method is exported so that unit tests can set the rest result with appropriate
// values as required.
func SetRestResult(ctx context.Context, result common.RestResult) {
raw := ctx.Value(common.RestResultContextKey{})
if raw == nil {
return
}
target := raw.(*common.RestResult)
target.Body = result.Body
target.Headers = result.Headers
target.StatusCode = result.StatusCode
}