-
Notifications
You must be signed in to change notification settings - Fork 0
/
httpresultswriter.go
344 lines (300 loc) · 10.2 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
package function
import (
"bytes"
"encoding/json"
"encoding/xml"
"fmt"
"io"
"net/http"
"github.com/h2non/filetype"
"github.com/h2non/filetype/types"
"github.com/ungerik/go-httpx/contenttype"
)
type HTTPResultsWriter interface {
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)
}
var RespondJSON HTTPResultsWriterFunc = func(results []any, resultErr error, response http.ResponseWriter, request *http.Request) error {
if resultErr != nil || request.Context().Err() != nil {
return resultErr
}
// no results, just 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
}
// RespondBinary responds with contentType using the binary data from results of type []byte, string, or io.Reader.
func RespondBinary(contentType string) HTTPResultsWriterFunc {
return func(results []any, resultErr error, response http.ResponseWriter, request *http.Request) (err error) {
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
}
}
func RespondJSONField(fieldName string) HTTPResultsWriterFunc {
return func(results []any, resultErr error, response http.ResponseWriter, request *http.Request) (err error) {
if resultErr != nil || request.Context().Err() != nil {
return resultErr
}
m := make(map[string]any)
if len(results) > 0 {
m[fieldName] = results[0]
}
j, err := encodeJSON(m)
if err != nil {
return err
}
response.Header().Set("Content-Type", contenttype.JSON)
_, err = response.Write(j)
return err
}
}
var RespondXML HTTPResultsWriterFunc = func(results []any, resultErr error, response http.ResponseWriter, request *http.Request) error {
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
}
var RespondPlaintext HTTPResultsWriterFunc = func(results []any, resultErr error, response http.ResponseWriter, request *http.Request) error {
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.PlainText)
_, err := response.Write(buf.Bytes())
return err
}
var RespondHTML HTTPResultsWriterFunc = func(results []any, resultErr error, response http.ResponseWriter, request *http.Request) error {
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 {
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 {
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 {
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 {
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 {
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 {
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 {
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 {
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 {
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)
}