forked from go-fuego/fuego
-
Notifications
You must be signed in to change notification settings - Fork 0
/
serialization.go
357 lines (307 loc) · 9.35 KB
/
serialization.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
package fuego
import (
"context"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"log/slog"
"net/http"
"reflect"
"strings"
"gopkg.in/yaml.v3"
)
// OutTransformer is an interface for entities that can be transformed.
// Useful for example for trimming strings, changing case, etc.
// Can also raise an error if the entity is not valid.
// Must be implemented by a POINTER RECEIVER.
// Example:
//
// type User struct {
// Name string `json:"name"`
// Password string `json:"password"`
// }
//
// // Not (u User) but (u *User)
//
// func (u *User) OutTransform(context.Context) error {
// u.Name = "M. " + u.Name
// u.Password = "*****"
// return nil
// }
type OutTransformer interface {
OutTransform(context.Context) error // Transforms an entity before sending it.
}
func transformOut[T any](ctx context.Context, ans T) (T, error) {
if reflect.TypeOf(ans).Kind() == reflect.Ptr {
// If ans is a nil pointer, we do not want to transform it.
if reflect.ValueOf(ans).IsNil() {
return ans, nil
}
outTransformer, ok := any(ans).(OutTransformer)
if !ok {
return ans, nil
}
err := outTransformer.OutTransform(ctx)
if err != nil {
return ans, err
}
return outTransformer.(T), nil
}
_, ok := any(ans).(OutTransformer)
if ok {
return ans, errors.New("OutTransformer must be implemented by a POINTER RECEIVER. Please read the [OutTransformer] documentation")
}
outTransformer, ok := any(&ans).(OutTransformer)
if !ok {
return ans, nil
}
err := outTransformer.OutTransform(ctx)
if err != nil {
return ans, err
}
ans = *any(outTransformer).(*T)
return ans, nil
}
type Sender func(http.ResponseWriter, *http.Request, any) error
// Send sends a response.
// The format is determined by the Accept header.
// If Accept header `*/*` is found Send will Attempt to send
// HTML, and then JSON.
func Send(w http.ResponseWriter, r *http.Request, ans any) (err error) {
for _, header := range parseAcceptHeader(r.Header) {
switch inferAcceptHeader(header, ans) {
case "application/xml":
err = SendXML(w, nil, ans)
case "text/html":
err = SendHTML(w, r, ans)
case "text/plain":
err = SendText(w, nil, ans)
case "application/json":
err = SendJSON(w, nil, ans)
case "application/x-yaml", "text/yaml; charset=utf-8", "application/yaml": // https://www.rfc-editor.org/rfc/rfc9512.html
err = SendYAML(w, nil, ans)
default:
// if we don't support the header, try the next one
continue
}
if err == nil {
return nil
}
}
if err != nil {
return err
}
return errors.New("no supported Accept header was not provided from: " + r.Header.Get("Accept"))
}
// SendYAML sends a YAML response.
// Declared as a variable to be able to override it for clients that need to customize serialization.
var SendYAML = func(w http.ResponseWriter, _ *http.Request, ans any) error {
w.Header().Set("Content-Type", "application/x-yaml")
err := yaml.NewEncoder(w).Encode(ans)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
slog.Error("Cannot serialize returned response to YAML", "error", err)
_, _ = w.Write([]byte(`{"error":"Cannot serialize returned response to YAML"}`))
}
return err
}
// SendYAMLError sends a YAML error response.
// If the error implements ErrorWithStatus, the status code will be set.
func SendYAMLError(w http.ResponseWriter, _ *http.Request, err error) {
status := http.StatusInternalServerError
var errorStatus ErrorWithStatus
if errors.As(err, &errorStatus) {
status = errorStatus.StatusCode()
}
w.WriteHeader(status)
_ = SendYAML(w, nil, err.Error())
}
// SendJSON sends a JSON response.
// Declared as a variable to be able to override it for clients that need to customize serialization.
var SendJSON = func(w http.ResponseWriter, _ *http.Request, ans any) error {
w.Header().Set("Content-Type", "application/json")
err := json.NewEncoder(w).Encode(ans)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
slog.Error("Cannot serialize returned response to JSON", "error", err)
_, _ = w.Write([]byte(`{"error":"Cannot serialize returned response to JSON"}`))
}
return err
}
type ErrorSender = func(http.ResponseWriter, *http.Request, error)
// SendError sends an error.
// Declared as a variable to be able to override it for clients that need to customize serialization.
var SendError = func(w http.ResponseWriter, r *http.Request, err error) {
for _, header := range parseAcceptHeader(r.Header) {
switch inferAcceptHeader(header, nil) {
case "application/xml":
SendXMLError(w, nil, err)
case "text/html":
SendHTMLError(w, nil, err)
case "text/plain":
SendTextError(w, r, err)
case "application/json":
SendJSONError(w, nil, err)
case "application/x-yaml", "text/yaml; charset=utf-8", "application/yaml": // https://www.rfc-editor.org/rfc/rfc9512.html
SendYAMLError(w, nil, err)
default:
continue
}
return
}
SendJSONError(w, r, err)
}
// SendJSONError sends a JSON error response.
// If the error implements ErrorWithStatus, the status code will be set.
func SendJSONError(w http.ResponseWriter, _ *http.Request, err error) {
status := http.StatusInternalServerError
var errorStatus ErrorWithStatus
if errors.As(err, &errorStatus) {
status = errorStatus.StatusCode()
}
w.Header().Set("Content-Type", "application/json")
var httpError HTTPError
if errors.As(err, &httpError) {
w.Header().Set("Content-Type", "application/problem+json")
}
w.WriteHeader(status)
_ = SendJSON(w, nil, err)
}
// SendXML sends a XML response.
// Declared as a variable to be able to override it for clients that need to customize serialization.
var SendXML = func(w http.ResponseWriter, _ *http.Request, ans any) error {
w.Header().Set("Content-Type", "application/xml")
return xml.NewEncoder(w).Encode(ans)
}
// SendXMLError sends a XML error response.
// If the error implements ErrorWithStatus, the status code will be set.
func SendXMLError(w http.ResponseWriter, _ *http.Request, err error) {
status := http.StatusInternalServerError
var errorStatus ErrorWithStatus
if errors.As(err, &errorStatus) {
status = errorStatus.StatusCode()
}
w.WriteHeader(status)
err = SendXML(w, nil, err)
if err != nil {
slog.Error("Cannot serialize returned response to XML", "error", err)
_, _ = w.Write([]byte(`{"error":"Cannot serialize returned response to XML"}`))
}
}
// SendHTML sends a HTML response.
// Declared as a variable to be able to override it for clients that need to customize serialization.
var SendHTML = func(w http.ResponseWriter, r *http.Request, ans any) error {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
ctxRenderer, ok := any(ans).(CtxRenderer)
if ok {
return ctxRenderer.Render(r.Context(), w)
}
renderer, ok := any(ans).(Renderer)
if ok {
return renderer.Render(w)
}
html, ok := any(ans).(HTML)
if ok {
_, err := w.Write([]byte(html))
return err
}
htmlString, ok := any(ans).(string)
if ok {
_, err := w.Write([]byte(htmlString))
return err
}
// The type cannot be converted to HTML
return fmt.Errorf("cannot serialize HTML from type %T (not string, fuego.HTML and does not implement fuego.CtxRenderer or fuego.Renderer)", ans)
}
// SendHTMLError sends a HTML response.
// If the error implements ErrorWithStatus, the status code will be set.
func SendHTMLError(w http.ResponseWriter, _ *http.Request, err error) {
status := http.StatusInternalServerError
var errorStatus ErrorWithStatus
if errors.As(err, &errorStatus) {
status = errorStatus.StatusCode()
}
w.WriteHeader(status)
_ = SendHTML(w, nil, err.Error())
}
// SendText sends a HTML response.
// Declared as a variable to be able to override it for clients that need to customize serialization.
func SendText(w http.ResponseWriter, _ *http.Request, ans any) error {
var err error
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
stringToWrite, ok := any(ans).(string)
if !ok {
stringToWritePtr, okPtr := any(ans).(*string)
if okPtr {
stringToWrite = *stringToWritePtr
} else {
stringToWrite = fmt.Sprintf("%v", ans)
}
}
_, err = w.Write([]byte(stringToWrite))
return err
}
// SendTextError sends a Text response.
// If the error implements ErrorWithStatus, the status code will be set.
func SendTextError(w http.ResponseWriter, _ *http.Request, err error) {
status := http.StatusInternalServerError
var errorStatus ErrorWithStatus
if errors.As(err, &errorStatus) {
status = errorStatus.StatusCode()
}
w.WriteHeader(status)
_ = SendText(w, nil, err.Error())
}
func InferAcceptHeaderFromType(ans any) string {
_, ok := any(ans).(string)
if ok {
return "text/plain"
}
_, ok = any(ans).(*string)
if ok {
return "text/plain"
}
_, ok = any(ans).(HTML)
if ok {
return "text/html"
}
_, ok = any(ans).(CtxRenderer)
if ok {
return "text/html"
}
_, ok = any(&ans).(*CtxRenderer)
if ok {
return "text/html"
}
_, ok = any(ans).(Renderer)
if ok {
return "text/html"
}
_, ok = any(&ans).(*Renderer)
if ok {
return "text/html"
}
return "application/json"
}
func inferAcceptHeader(accept string, ans any) string {
if accept == "" || accept == "*/*" {
return InferAcceptHeaderFromType(ans)
}
return accept
}
func parseAcceptHeader(header http.Header) []string {
accept := header.Get("Accept")
if accept == "" {
return []string{""}
}
vals := strings.Split(accept, ",")
for i, v := range vals {
// ignore quality parameters if they exist
index := strings.Index(v, ";")
if index > 0 {
vals[i] = v[:index]
}
}
return vals
}