-
Notifications
You must be signed in to change notification settings - Fork 14
/
restlib.go
220 lines (192 loc) · 5.73 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
package restlib
import (
"bytes"
"compress/gzip"
"context"
"encoding/json"
"encoding/xml"
"io"
"io/ioutil"
"net/http"
"reflect"
"regexp"
"strings"
"github.com/anz-bank/sysl-go/common"
"github.com/pkg/errors"
)
// 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
}
// DoHTTPRequest returns HTTPResult.
//nolint:funlen // TODO: Refactor this function to be shorter.
func DoHTTPRequest(ctx context.Context, client *http.Client, method string,
urlString string, body interface{}, required []string,
okResponse interface{}, errorResponse interface{}) (*HTTPResult, error) {
var reader io.Reader
headers := common.RequestHeaderFromContext(ctx)
contentType := headers.Get("Content-Type")
// Validations 1:
// If we have body, marshal it to json
if body != nil {
if strings.Contains(contentType, "xml") {
var strBody string
strBody = reflect.ValueOf(body).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)
} else {
reqJSON, err := json.Marshal(body)
if err != nil {
return nil, err
}
reader = bytes.NewReader(reqJSON)
}
}
// Validations 2:
// if we have required headers, see if they have been passed to us
for _, key := range required {
if has := headers.Get(key); has == "" {
return nil, errors.Errorf("Missing Required header: %s", key)
}
}
httpRequest, err := http.NewRequest(method, urlString, reader)
if err != nil {
return nil, err
}
httpRequest.Header = headers
httpResponse, err := client.Do(httpRequest.WithContext(ctx))
if err != nil {
return nil, err
}
defer httpResponse.Body.Close()
var bodyReader io.Reader
if m, _ := regexp.MatchString(`(?i)gzip`, httpResponse.Header.Get("Content-Encoding")); m {
bodyReader, err = gzip.NewReader(httpResponse.Body)
if err != nil {
return nil, err
}
} else {
bodyReader = httpResponse.Body
}
respBody, err := ioutil.ReadAll(bodyReader)
if err != nil {
return nil, err
}
// OK
switch httpResponse.StatusCode {
case http.StatusOK,
http.StatusCreated,
http.StatusAccepted,
http.StatusNonAuthoritativeInfo,
http.StatusNoContent,
http.StatusResetContent:
return unmarshal(httpResponse, respBody, okResponse)
}
// Error
result, err := unmarshal(httpResponse, respBody, errorResponse)
if err != nil {
return nil, err
}
// 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 {
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, "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.
func OnRestResultHTTPResult(ctx context.Context, result *HTTPResult, err error) {
var restResult *common.RestResult = nil
if result != nil && result.HTTPResponse != nil {
restResult = &common.RestResult{
StatusCode: result.HTTPResponse.StatusCode,
Headers: result.HTTPResponse.Header,
Body: result.Body,
}
}
OnRestResult(ctx, restResult, err)
}
// OnRestResult method will be called from tests as we don't expose the HTTPResult itself.
func OnRestResult(ctx context.Context, result *common.RestResult, err error) {
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
}