forked from gofiber/fiber
-
Notifications
You must be signed in to change notification settings - Fork 0
/
earlydata.go
52 lines (42 loc) · 1.16 KB
/
earlydata.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
package earlydata
import (
"github.com/boomhut/fiber/v3"
)
// The contextKey type is unexported to prevent collisions with context keys defined in
// other packages.
type contextKey int
const (
localsKeyAllowed contextKey = 0 // earlydata_allowed
)
// IsEarlyData returns true if the request is an early-data request
func IsEarly(c fiber.Ctx) bool {
return c.Locals(localsKeyAllowed) != nil
}
// New creates a new middleware handler
// https://datatracker.ietf.org/doc/html/rfc8470#section-5.1
func New(config ...Config) fiber.Handler {
// Set default config
cfg := configDefault(config...)
// Return new handler
return func(c fiber.Ctx) error {
// Don't execute middleware if Next returns true
if cfg.Next != nil && cfg.Next(c) {
return c.Next()
}
// Abort if we can't trust the early-data header
if !c.IsProxyTrusted() {
return cfg.Error
}
// Continue stack if request is not an early-data request
if !cfg.IsEarlyData(c) {
return c.Next()
}
// Continue stack if we allow early-data for this request
if cfg.AllowEarlyData(c) {
_ = c.Locals(localsKeyAllowed, true)
return c.Next()
}
// Else return our error
return cfg.Error
}
}