-
-
Notifications
You must be signed in to change notification settings - Fork 45
/
ctx.go
478 lines (408 loc) · 15.2 KB
/
ctx.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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
package fuego
import (
"context"
"fmt"
"html/template"
"io"
"io/fs"
"log/slog"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
const (
maxBodySize = 1048576
)
// ctx is the context of the request.
// It contains the request body, the path parameters, the query parameters, and the HTTP request.
// Please do not use a pointer type as parameter.
type ctx[B any] interface {
// Body returns the body of the request.
// If (*B) implements [InTransformer], it will be transformed after deserialization.
// It caches the result, so it can be called multiple times.
Body() (B, error)
// MustBody works like Body, but panics if there is an error.
MustBody() B
// PathParam returns the path parameter with the given name.
// If it does not exist, it returns an empty string.
// Example:
// fuego.Get(s, "/recipes/{recipe_id}", func(c fuego.ContextNoBody) (any, error) {
// id := c.PathParam("recipe_id")
// ...
// })
PathParam(name string) string
QueryParam(name string) string
QueryParamArr(name string) []string
QueryParamInt(name string) int // If the query parameter is not provided or is not an int, it returns the default given value. Use [Ctx.QueryParamIntErr] if you want to know if the query parameter is erroneous.
QueryParamIntErr(name string) (int, error)
QueryParamBool(name string) bool // If the query parameter is not provided or is not a bool, it returns the default given value. Use [Ctx.QueryParamBoolErr] if you want to know if the query parameter is erroneous.
QueryParamBoolErr(name string) (bool, error)
QueryParams() url.Values
MainLang() string // ex: fr. MainLang returns the main language of the request. It is the first language of the Accept-Language header. To get the main locale (ex: fr-CA), use [Ctx.MainLocale].
MainLocale() string // ex: en-US. MainLocale returns the main locale of the request. It is the first locale of the Accept-Language header. To get the main language (ex: en), use [Ctx.MainLang].
// Render renders the given templates with the given data.
// Example:
// fuego.Get(s, "/recipes", func(c fuego.ContextNoBody) (any, error) {
// recipes, _ := rs.Queries.GetRecipes(c.Context())
// ...
// return c.Render("pages/recipes.page.html", recipes)
// })
// For the Go templates reference, see https://pkg.go.dev/html/template
//
// [templateGlobsToOverride] is a list of templates to override.
// For example, if you have 2 conflicting templates
// - with the same name "partials/aaa/nav.partial.html" and "partials/bbb/nav.partial.html"
// - or two templates with different names, but that define the same block "page" for example,
// and you want to override one above the other, you can do:
// c.Render("admin.page.html", recipes, "partials/aaa/nav.partial.html")
// By default, [templateToExecute] is added to the list of templates to override.
Render(templateToExecute string, data any, templateGlobsToOverride ...string) (CtxRenderer, error)
Cookie(name string) (*http.Cookie, error) // Get request cookie
SetCookie(cookie http.Cookie) // Sets response cookie
Header(key string) string // Get request header
SetHeader(key, value string) // Sets response header
Context() context.Context
Request() *http.Request // Request returns the underlying HTTP request.
Response() http.ResponseWriter // Response returns the underlying HTTP response writer.
// SetStatus sets the status code of the response.
// Alias to http.ResponseWriter.WriteHeader.
SetStatus(code int)
// Redirect redirects to the given url with the given status code.
// Example:
// fuego.Get(s, "/recipes", func(c fuego.ContextNoBody) (any, error) {
// ...
// return c.Redirect(301, "/recipes-list")
// })
Redirect(code int, url string) (any, error)
}
// NewContext returns a new context. It is used internally by Fuego. You probably want to use Ctx[B] instead.
func NewContext[B any](w http.ResponseWriter, r *http.Request, options readOptions) *ContextWithBody[B] {
c := &ContextWithBody[B]{
ContextNoBody: ContextNoBody{
Res: w,
Req: r,
readOptions: readOptions{
DisallowUnknownFields: options.DisallowUnknownFields,
MaxBodySize: options.MaxBodySize,
},
urlValues: r.URL.Query(),
},
}
return c
}
// ContextWithBody is the same as fuego.ContextNoBody, but
// has a Body. The Body type parameter represents the expected data type
// from http.Request.Body. Please do not use a pointer as a type parameter.
type ContextWithBody[Body any] struct {
body *Body // Cache the body in request context, because it is not possible to read an HTTP request body multiple times.
ContextNoBody
}
// ContextNoBody is used when the controller does not have a body.
// It is used as a base context for other Context types.
type ContextNoBody struct {
Req *http.Request
Res http.ResponseWriter
fs fs.FS
templates *template.Template
params map[string]OpenAPIParam // list of expected query parameters (declared in the OpenAPI spec)
urlValues url.Values
readOptions readOptions
}
var (
_ ctx[any] = ContextNoBody{} // Check that ContextNoBody implements Ctx.
_ context.Context = ContextNoBody{} // Check that ContextNoBody implements context.Context.
)
func (c ContextNoBody) Body() (any, error) {
slog.Warn("this method should not be called. It probably happened because you passed the context to another controller.")
return body[map[string]any](c)
}
func (c ContextNoBody) MustBody() any {
b, err := c.Body()
if err != nil {
panic(err)
}
return b
}
// SetStatus sets the status code of the response.
// Alias to http.ResponseWriter.WriteHeader.
func (c ContextNoBody) SetStatus(code int) {
c.Res.WriteHeader(code)
}
// readOptions are options for reading the request body.
type readOptions struct {
DisallowUnknownFields bool
MaxBodySize int64
LogBody bool
}
var (
_ ctx[any] = &ContextWithBody[any]{} // Check that ContextWithBody[any] implements Ctx.
_ ctx[string] = &ContextWithBody[string]{} // Check that ContextWithBody[string] implements Ctx.
_ ctx[any] = &ContextNoBody{} // Check that ContextNoBody implements Ctx.
_ ctx[any] = ContextNoBody{} // Check that ContextNoBody implements Ctx.
)
func (c ContextNoBody) Redirect(code int, url string) (any, error) {
http.Redirect(c.Res, c.Req, url, code)
return nil, nil
}
// ContextNoBody implements the context interface via [net/http.Request.Context]
func (c ContextNoBody) Deadline() (deadline time.Time, ok bool) {
return c.Req.Context().Deadline()
}
// ContextNoBody implements the context interface via [net/http.Request.Context]
func (c ContextNoBody) Done() <-chan struct{} {
return c.Req.Context().Done()
}
// ContextNoBody implements the context interface via [net/http.Request.Context]
func (c ContextNoBody) Err() error {
return c.Req.Context().Err()
}
// ContextNoBody implements the context interface via [net/http.Request.Context]
func (c ContextNoBody) Value(key any) any {
return c.Req.Context().Value(key)
}
// ContextNoBody implements the context interface via [net/http.Request.Context]
func (c ContextNoBody) Context() context.Context {
return c.Req.Context()
}
// Get request header
func (c ContextNoBody) Header(key string) string {
return c.Request().Header.Get(key)
}
// Sets response header
func (c ContextNoBody) SetHeader(key, value string) {
c.Response().Header().Set(key, value)
}
// Get request cookie
func (c ContextNoBody) Cookie(name string) (*http.Cookie, error) {
return c.Request().Cookie(name)
}
// Sets response cookie
func (c ContextNoBody) SetCookie(cookie http.Cookie) {
http.SetCookie(c.Response(), &cookie)
}
// Render renders the given templates with the given data.
// It returns just an empty string, because the response is written directly to the http.ResponseWriter.
//
// Init templates if not already done.
// This has the side effect of making the Render method static, meaning
// that the templates will be parsed only once, removing
// the need to parse the templates on each request but also preventing
// to dynamically use new templates.
func (c ContextNoBody) Render(templateToExecute string, data any, layoutsGlobs ...string) (CtxRenderer, error) {
return &StdRenderer{
templateToExecute: templateToExecute,
templates: c.templates,
layoutsGlobs: layoutsGlobs,
fs: c.fs,
data: data,
}, nil
}
// PathParams returns the path parameters of the request.
func (c ContextNoBody) PathParam(name string) string {
return c.Req.PathValue(name)
}
type QueryParamNotFoundError struct {
ParamName string
}
func (e QueryParamNotFoundError) Error() string {
return fmt.Errorf("param %s not found", e.ParamName).Error()
}
type QueryParamInvalidTypeError struct {
ParamName string
ParamValue string
ExpectedType string
Err error
}
func (e QueryParamInvalidTypeError) Error() string {
return fmt.Errorf("param %s=%s is not of type %s: %w", e.ParamName, e.ParamValue, e.ExpectedType, e.Err).Error()
}
// QueryParams returns the query parameters of the request. It is a shortcut for c.Req.URL.Query().
func (c ContextNoBody) QueryParams() url.Values {
return c.urlValues
}
// QueryParamsArr returns an slice of string from the given query parameter.
func (c ContextNoBody) QueryParamArr(name string) []string {
_, ok := c.params[name]
if !ok {
slog.Warn("query parameter not expected in OpenAPI spec", "param", name)
}
return c.urlValues[name]
}
// QueryParam returns the query parameter with the given name.
// If it does not exist, it returns an empty string, unless there is a default value declared in the OpenAPI spec.
//
// Example:
//
// fuego.Get(s, "/test", myController,
// option.Query("name", "Name", param.Default("hey"))
// )
func (c ContextNoBody) QueryParam(name string) string {
_, ok := c.params[name]
if !ok {
slog.Warn("query parameter not expected in OpenAPI spec", "param", name, "expected_one_of", c.params)
}
if !c.urlValues.Has(name) {
defaultValue, _ := c.params[name].Default.(string)
return defaultValue
}
return c.urlValues.Get(name)
}
func (c ContextNoBody) QueryParamIntErr(name string) (int, error) {
param := c.QueryParam(name)
if param == "" {
defaultValue, ok := c.params[name].Default.(int)
if ok {
return defaultValue, nil
}
return 0, QueryParamNotFoundError{ParamName: name}
}
i, err := strconv.Atoi(param)
if err != nil {
return 0, QueryParamInvalidTypeError{
ParamName: name,
ParamValue: param,
ExpectedType: "int",
Err: err,
}
}
return i, nil
}
// QueryParamInt returns the query parameter with the given name as an int.
// If it does not exist, it returns the default value declared in the OpenAPI spec.
// For example, if the query parameter is declared as:
//
// fuego.Get(s, "/test", myController,
// option.QueryInt("page", "Page number", param.Default(1))
// )
//
// and the query parameter does not exist, it will return 1.
// If the query parameter does not exist and there is no default value, or if it is not an int, it returns 0.
func (c ContextNoBody) QueryParamInt(name string) int {
param, err := c.QueryParamIntErr(name)
if err != nil {
return 0
}
return param
}
// QueryParamBool returns the query parameter with the given name as a bool.
// If the query parameter does not exist or is not a bool, it returns the default value declared in the OpenAPI spec.
// For example, if the query parameter is declared as:
//
// fuego.Get(s, "/test", myController,
// option.QueryBool("is_ok", "Is OK?", param.Default(true))
// )
//
// and the query parameter does not exist in the HTTP request, it will return true.
// Accepted values are defined as [strconv.ParseBool]
func (c ContextNoBody) QueryParamBoolErr(name string) (bool, error) {
param := c.QueryParam(name)
if param == "" {
defaultValue, ok := c.params[name].Default.(bool)
if ok {
return defaultValue, nil
}
return false, QueryParamNotFoundError{ParamName: name}
}
b, err := strconv.ParseBool(param)
if err != nil {
return false, QueryParamInvalidTypeError{
ParamName: name,
ParamValue: param,
ExpectedType: "bool",
Err: err,
}
}
return b, nil
}
// QueryParamBool returns the query parameter with the given name as a bool.
// If the query parameter does not exist or is not a bool, it returns false.
// Accepted values are defined as [strconv.ParseBool]
// Example:
//
// fuego.Get(s, "/test", myController,
// option.QueryBool("is_ok", "Is OK?", param.Default(true))
// )
//
// and the query parameter does not exist in the HTTP request, it will return true.
func (c ContextNoBody) QueryParamBool(name string) bool {
param, err := c.QueryParamBoolErr(name)
if err != nil {
return false
}
return param
}
func (c ContextNoBody) MainLang() string {
return strings.Split(c.MainLocale(), "-")[0]
}
func (c ContextNoBody) MainLocale() string {
return strings.Split(c.Req.Header.Get("Accept-Language"), ",")[0]
}
// Request returns the HTTP request.
func (c ContextNoBody) Request() *http.Request {
return c.Req
}
// Response returns the HTTP response writer.
func (c ContextNoBody) Response() http.ResponseWriter {
return c.Res
}
// MustBody works like Body, but panics if there is an error.
func (c *ContextWithBody[B]) MustBody() B {
b, err := c.Body()
if err != nil {
panic(err)
}
return b
}
// Body returns the body of the request.
// If (*B) implements [InTransformer], it will be transformed after deserialization.
// It caches the result, so it can be called multiple times.
// The reason the body is cached is that it is impossible to read an HTTP request body multiple times, not because of performance.
// For decoding, it uses the Content-Type header. If it is not set, defaults to application/json.
func (c *ContextWithBody[B]) Body() (B, error) {
if c.body != nil {
return *c.body, nil
}
body, err := body[B](c.ContextNoBody)
c.body = &body
return body, err
}
func body[B any](c ContextNoBody) (B, error) {
// Limit the size of the request body.
if c.readOptions.MaxBodySize != 0 {
c.Req.Body = http.MaxBytesReader(nil, c.Req.Body, c.readOptions.MaxBodySize)
}
timeDeserialize := time.Now()
var body B
var err error
switch c.Req.Header.Get("Content-Type") {
case "text/plain":
s, errReadingString := readString[string](c.Req.Context(), c.Req.Body, c.readOptions)
body = any(s).(B)
err = errReadingString
case "application/x-www-form-urlencoded", "multipart/form-data":
body, err = readURLEncoded[B](c.Req, c.readOptions)
case "application/xml":
body, err = readXML[B](c.Req.Context(), c.Req.Body, c.readOptions)
case "application/x-yaml", "text/yaml; charset=utf-8", "application/yaml": // https://www.rfc-editor.org/rfc/rfc9512.html
body, err = readYAML[B](c.Req.Context(), c.Req.Body, c.readOptions)
case "application/octet-stream":
// Read c.Req Body to bytes
bytes, err := io.ReadAll(c.Req.Body)
if err != nil {
return body, err
}
respBytes, ok := any(bytes).(B)
if !ok {
return body, fmt.Errorf("could not convert bytes to %T. To read binary data from the request, use []byte as the body type", body)
}
body = respBytes
case "application/json":
fallthrough
default:
body, err = readJSON[B](c.Req.Context(), c.Req.Body, c.readOptions)
}
c.Res.Header().Add("Server-Timing", Timing{"deserialize", time.Since(timeDeserialize), "controller > deserialize"}.String())
return body, err
}