-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttpresultswriter.go
397 lines (352 loc) · 13 KB
/
httpresultswriter.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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
package function
import (
"bytes"
"encoding/json"
"encoding/xml"
"fmt"
"io"
"net/http"
"slices"
"github.com/h2non/filetype"
"github.com/h2non/filetype/types"
"github.com/ungerik/go-httpx/contenttype"
)
// HTTPResultsWriter implementations write the results of a function call to an HTTP response.
type HTTPResultsWriter interface {
// WriteResults writes the results and optionally the resultErr to the response.
// If the method does not handle the resultErr then it should return it
// so it can be handled by the next writer in the chain.
WriteResults(results []any, resultErr error, response http.ResponseWriter, request *http.Request) error
}
type HTTPResultsWriterFunc func(results []any, resultErr error, response http.ResponseWriter, request *http.Request) error
func (f HTTPResultsWriterFunc) WriteResults(results []any, resultErr error, response http.ResponseWriter, request *http.Request) error {
return f(results, resultErr, response, request)
}
// RespondJSON writes the results of a function call as a JSON to the response.
// If the function returns one non-error result then it is marshalled as is.
// If the function returns multiple results then they are marshalled as a JSON array.
// If the function returns an resultErr then it is returned by this method,
// so it can be handled by the next writer in the chain.
// Any resultErr is not handled and will be returned by this method.
var RespondJSON HTTPResultsWriterFunc = func(results []any, resultErr error, response http.ResponseWriter, request *http.Request) error {
// Don't handle resultErr or context cancellation
if resultErr != nil || request.Context().Err() != nil {
return resultErr
}
// no results, just respond with HTTP status 200: OK
if len(results) == 0 {
return nil
}
var r any
if len(results) == 1 {
// only one result, write it as is
r = results[0]
} else {
// multiple results, put them in a JSON array
r = results
}
j, err := encodeJSON(r)
if err != nil {
return err
}
response.Header().Set("Content-Type", contenttype.JSON)
_, err = response.Write(j)
return err
}
// RespondJSONObject writes the results of a function call as a JSON object to the response.
// The resultKeys are the keys of the JSON object, naming the function results in order.
//
// If the last result is an error and the resultKeys don't have a key for it
// then the error is returned unhandled if not nil.
// If there is a result key for the error then the error
// is marshalled as JSON string and not returned.
//
// An error is returned if the number of results does not match the number of resultKeys
// or number of resultKeys minus one if the last result is an error.
func RespondJSONObject(resultKeys ...string) HTTPResultsWriterFunc {
if len(slices.Compact(resultKeys)) != len(resultKeys) {
panic(fmt.Sprintf("RespondJSONObject resultKeys contains duplicates: %#v", resultKeys))
}
return func(results []any, resultErr error, response http.ResponseWriter, request *http.Request) error {
// Early return on context cancellation
if request.Context().Err() != nil {
return resultErr
}
errorHasKey := len(resultKeys) == len(results)+1
if !errorHasKey && resultErr != nil {
return resultErr
}
if len(resultKeys) != len(results) && !errorHasKey {
return fmt.Errorf("RespondJSONObject expects %d results for %v, got %d", len(resultKeys), resultKeys, len(results))
}
r := make(map[string]any)
for i, result := range results {
r[resultKeys[i]] = result
}
if errorHasKey {
r[resultKeys[len(resultKeys)-1]] = resultErr.Error()
}
j, err := encodeJSON(r)
if err != nil {
return err
}
response.Header().Set("Content-Type", contenttype.JSON)
_, err = response.Write(j)
return err
}
}
// RespondBinary responds with contentType using the binary data from results of type []byte, string, or io.Reader.
// Any resultErr is not handled and will be returned by this method.
func RespondBinary(contentType string) HTTPResultsWriterFunc {
return func(results []any, resultErr error, response http.ResponseWriter, request *http.Request) (err error) {
// Don't handle resultErr or context cancellation
if resultErr != nil || request.Context().Err() != nil {
return resultErr
}
var buf bytes.Buffer
for _, result := range results {
switch data := result.(type) {
case []byte:
_, err = buf.Write(data)
case string:
_, err = buf.WriteString(data)
case io.Reader:
_, err = io.Copy(&buf, data)
default:
return fmt.Errorf("RespondBinary does not support result type %T", result)
}
if err != nil {
return err
}
}
response.Header().Set("Content-Type", contentType)
_, err = response.Write(buf.Bytes())
return err
}
}
var RespondXML HTTPResultsWriterFunc = func(results []any, resultErr error, response http.ResponseWriter, request *http.Request) error {
// Don't handle resultErr or context cancellation
if resultErr != nil || request.Context().Err() != nil {
return resultErr
}
var buf []byte
for i, result := range results {
if i > 0 {
buf = append(buf, '\n')
}
b, err := encodeXML(result)
if err != nil {
return err
}
buf = append(buf, b...)
}
response.Header().Set("Content-Type", contenttype.XML)
_, err := response.Write(buf)
return err
}
// RespondPlaintext writes the results of a function call as a plaintext to the response
// using fmt.Fprint to format the results.
// Spaces are added between results when neither is a string.
// Any resultErr is not handled and will be returned by this method.
var RespondPlaintext HTTPResultsWriterFunc = func(results []any, resultErr error, response http.ResponseWriter, request *http.Request) error {
// Don't handle resultErr or context cancellation
if resultErr != nil || request.Context().Err() != nil {
return resultErr
}
var buf bytes.Buffer
fmt.Fprint(&buf, results...)
response.Header().Add("Content-Type", contenttype.PlainText)
_, err := response.Write(buf.Bytes())
return err
}
var RespondHTML HTTPResultsWriterFunc = func(results []any, resultErr error, response http.ResponseWriter, request *http.Request) error {
// Don't handle resultErr or context cancellation
if resultErr != nil || request.Context().Err() != nil {
return resultErr
}
var buf bytes.Buffer
for _, result := range results {
if b, ok := result.([]byte); ok {
buf.Write(b)
} else {
fmt.Fprint(&buf, result)
}
}
response.Header().Add("Content-Type", contenttype.HTML)
_, err := response.Write(buf.Bytes())
return err
}
var RespondDetectContentType HTTPResultsWriterFunc = func(results []any, resultErr error, response http.ResponseWriter, request *http.Request) error {
// Don't handle resultErr or context cancellation
if resultErr != nil || request.Context().Err() != nil {
return resultErr
}
if len(results) != 1 {
return fmt.Errorf("RespondDetectContentType needs 1 result, got %d", len(results))
}
data, ok := results[0].([]byte)
if !ok {
return fmt.Errorf("RespondDetectContentType needs []byte result, got %T", results[0])
}
response.Header().Add("Content-Type", DetectContentType(data))
_, err := response.Write(data)
return err
}
func RespondContentType(contentType string) HTTPResultsWriter {
return HTTPResultsWriterFunc(func(results []any, resultErr error, response http.ResponseWriter, request *http.Request) error {
// Don't handle resultErr or context cancellation
if resultErr != nil || request.Context().Err() != nil {
return resultErr
}
if len(results) != 1 {
return fmt.Errorf("RespondContentType(%s) needs 1 result, got %d: %#v", contentType, len(results), results)
}
data, ok := results[0].([]byte)
if !ok {
return fmt.Errorf("RespondContentType(%s) needs []byte result, got %T", contentType, results[0])
}
response.Header().Add("Content-Type", contentType)
_, err := response.Write(data)
return err
})
}
// DetectContentType tries to detect the MIME content-type of data,
// or returns "application/octet-stream" if none could be identified.
func DetectContentType(data []byte) string {
jsonData := map[string]any{}
jsonErr := json.Unmarshal(data, &jsonData)
if jsonErr == nil {
return "application/json"
}
kind, _ := filetype.Match(data)
if kind == types.Unknown {
return http.DetectContentType(data)
}
return kind.MIME.Value
}
func encodeJSON(response any) ([]byte, error) {
if PrettyPrint {
return json.MarshalIndent(response, "", PrettyPrintIndent)
}
return json.Marshal(response)
}
func encodeXML(response any) ([]byte, error) {
if PrettyPrint {
return xml.MarshalIndent(response, "", PrettyPrintIndent)
}
return xml.Marshal(response)
}
// Static content HTTPResultsWriter also implement http.Handler
var (
_ HTTPResultsWriter = RespondNothing
_ HTTPResultsWriter = RespondStaticHTML("")
_ HTTPResultsWriter = RespondStaticXML("")
_ HTTPResultsWriter = RespondStaticJSON("")
_ HTTPResultsWriter = RespondStaticPlaintext("")
_ HTTPResultsWriter = RespondRedirect("")
_ HTTPResultsWriter = RespondRedirectFunc(nil)
_ http.Handler = RespondNothing
_ http.Handler = RespondStaticHTML("")
_ http.Handler = RespondStaticXML("")
_ http.Handler = RespondStaticJSON("")
_ http.Handler = RespondStaticPlaintext("")
_ http.Handler = RespondRedirect("")
_ http.Handler = RespondRedirectFunc(nil)
)
var RespondNothing respondNothing
type respondNothing struct{}
func (respondNothing) WriteResults(results []any, resultErr error, response http.ResponseWriter, request *http.Request) error {
return resultErr
}
func (respondNothing) ServeHTTP(writer http.ResponseWriter, _ *http.Request) {}
type RespondStaticHTML string
func (html RespondStaticHTML) WriteResults(results []any, resultErr error, response http.ResponseWriter, request *http.Request) error {
// Don't handle resultErr or context cancellation
if resultErr != nil || request.Context().Err() != nil {
return resultErr
}
html.ServeHTTP(response, request)
return nil
}
func (html RespondStaticHTML) ServeHTTP(response http.ResponseWriter, _ *http.Request) {
response.Header().Add("Content-Type", contenttype.HTML)
response.Write([]byte(html)) //#nosec G104
}
type RespondStaticXML string
func (xml RespondStaticXML) WriteResults(results []any, resultErr error, response http.ResponseWriter, request *http.Request) error {
// Don't handle resultErr or context cancellation
if resultErr != nil || request.Context().Err() != nil {
return resultErr
}
xml.ServeHTTP(response, request)
return nil
}
func (xml RespondStaticXML) ServeHTTP(response http.ResponseWriter, _ *http.Request) {
response.Header().Set("Content-Type", contenttype.XML)
response.Write([]byte(xml)) //#nosec G104
}
type RespondStaticJSON string
func (json RespondStaticJSON) WriteResults(results []any, resultErr error, response http.ResponseWriter, request *http.Request) error {
// Don't handle resultErr or context cancellation
if resultErr != nil || request.Context().Err() != nil {
return resultErr
}
json.ServeHTTP(response, request)
return nil
}
func (json RespondStaticJSON) ServeHTTP(response http.ResponseWriter, _ *http.Request) {
response.Header().Set("Content-Type", contenttype.JSON)
response.Write([]byte(json)) //#nosec G104
}
type RespondStaticPlaintext string
func (text RespondStaticPlaintext) WriteResults(results []any, resultErr error, response http.ResponseWriter, request *http.Request) error {
// Don't handle resultErr or context cancellation
if resultErr != nil || request.Context().Err() != nil {
return resultErr
}
text.ServeHTTP(response, request)
return nil
}
func (text RespondStaticPlaintext) ServeHTTP(response http.ResponseWriter, _ *http.Request) {
response.Header().Add("Content-Type", contenttype.PlainText)
response.Write([]byte(text)) //#nosec G104
}
// RespondRedirect implements HTTPResultsWriter and http.Handler
// with for a redirect URL string.
// The redirect will be done with HTTP status code 302: Found.
type RespondRedirect string
func (re RespondRedirect) WriteResults(results []any, resultErr error, response http.ResponseWriter, request *http.Request) error {
// Don't handle resultErr or context cancellation
if resultErr != nil || request.Context().Err() != nil {
return resultErr
}
re.ServeHTTP(response, request)
return nil
}
func (re RespondRedirect) ServeHTTP(response http.ResponseWriter, request *http.Request) {
http.Redirect(response, request, string(re), http.StatusFound)
}
// RespondRedirectFunc implements HTTPResultsWriter and http.Handler
// with a function that returns the redirect URL.
// The redirect will be done with HTTP status code 302: Found.
type RespondRedirectFunc func(request *http.Request) (url string, err error)
func (f RespondRedirectFunc) WriteResults(results []any, resultErr error, response http.ResponseWriter, request *http.Request) error {
// Don't handle resultErr or context cancellation
if resultErr != nil || request.Context().Err() != nil {
return resultErr
}
url, err := f(request)
if err != nil {
return err
}
http.Redirect(response, request, url, http.StatusFound)
return nil
}
func (f RespondRedirectFunc) ServeHTTP(response http.ResponseWriter, request *http.Request) {
url, err := f(request)
if err != nil {
HandleErrorHTTP(err, response, request)
return
}
http.Redirect(response, request, url, http.StatusFound)
}