/
encode.go
56 lines (46 loc) · 1.2 KB
/
encode.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
package encoding
import (
"context"
"github.com/valyala/fasthttp"
)
type (
Marshaler = func(v any) ([]byte, error)
ContextMarshaler = func(ctx context.Context, v any) ([]byte, error)
ResponseEncoder = func(ctx *fasthttp.RequestCtx, v any) error
)
type EncoderConstraint interface {
Marshaler | ContextMarshaler | ResponseEncoder
}
// RegisterEncoder registers a response encoder on a given media type.
func RegisterEncoder[T EncoderConstraint](enc T, mime string, aliases ...string) {
switch e := any(enc).(type) {
case Marshaler:
encoders[mime] = func(ctx *fasthttp.RequestCtx, v any) error {
b, err := e(v)
if err != nil {
return err
}
ctx.Response.SetBodyRaw(b)
return nil
}
case ContextMarshaler:
encoders[mime] = func(ctx *fasthttp.RequestCtx, v any) error {
b, err := e(ctx, v)
if err != nil {
return err
}
ctx.Response.SetBodyRaw(b)
return nil
}
case ResponseEncoder:
encoders[mime] = e
}
for _, alias := range aliases {
encoders[alias] = encoders[mime]
}
}
// GetEncoder returns the response encoder for a given media type.
func GetEncoder(mime string) ResponseEncoder {
return encoders[mime]
}
var encoders = map[string]ResponseEncoder{}