-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserializer.go
More file actions
80 lines (60 loc) · 1.56 KB
/
serializer.go
File metadata and controls
80 lines (60 loc) · 1.56 KB
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
package kit
import (
"encoding/json"
"github.com/labstack/echo/v4"
"github.com/neoxelox/errors"
"github.com/neoxelox/kit/util"
)
// TODO: faster serializer (ffjson or sonic)
var (
ErrSerializerGeneric = errors.New("serializer failed")
)
var (
_SERIALIZER_DEFAULT_CONFIG = SerializerConfig{}
)
type SerializerConfig struct {
}
type Serializer struct {
config SerializerConfig
observer *Observer
}
func NewSerializer(observer *Observer, config SerializerConfig) *Serializer {
util.Merge(&config, _SERIALIZER_DEFAULT_CONFIG)
return &Serializer{
config: config,
observer: observer,
}
}
func (self *Serializer) Serialize(c echo.Context, i any, indent string) error {
encoder := json.NewEncoder(c.Response())
if indent != "" {
encoder.SetIndent("", indent)
}
encoder.SetEscapeHTML(false)
err := encoder.Encode(i)
if err != nil {
return ErrSerializerGeneric.Raise().Cause(err)
}
return nil
}
func (self *Serializer) Deserialize(c echo.Context, i any) error {
decoder := json.NewDecoder(c.Request().Body)
err := decoder.Decode(i)
if err != nil {
if ute, ok := err.(*json.UnmarshalTypeError); ok {
return ErrSerializerGeneric.Raise().
With("unmarshal type error").
Extra(map[string]any{
"field": ute.Field, "expected": ute.Type, "actual": ute.Value, "offset": ute.Offset}).
Cause(ute)
}
if se, ok := err.(*json.SyntaxError); ok {
return ErrSerializerGeneric.Raise().
With("syntax error").
Extra(map[string]any{"offset": se.Offset}).
Cause(se)
}
return ErrSerializerGeneric.Raise().Cause(err)
}
return nil
}