forked from hairyhenderson/gomplate
-
Notifications
You must be signed in to change notification settings - Fork 1
/
serialize.go
67 lines (59 loc) · 1.49 KB
/
serialize.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
package gomplate
import (
"time"
"github.com/google/uuid"
"github.com/ohler55/ojg"
"github.com/ohler55/ojg/alt"
"github.com/ohler55/ojg/jp"
"github.com/ohler55/ojg/oj"
)
var opts = oj.Options{
Color: false,
InitSize: 256,
CreateKey: "",
FullTypePath: false,
OmitNil: false,
OmitEmpty: false,
UseTags: true,
KeyExact: true,
NestEmbed: false,
BytesAs: ojg.BytesAsString,
TimeFormat: "time",
WriteLimit: 1024,
}
type AsMapper interface {
AsMap(fields ...string) map[string]any
}
// Serialize iterates over each key-value pair in the input map
// serializes any struct value to map[string]any.
func Serialize(in map[string]any) (map[string]any, error) {
if in == nil {
return nil, nil
}
// cel supports time.Duration natively - save original and then replace it after decomposition
// FIXME: This does not work for anything inside Structs
nativeTypes := make(map[string]any, len(in))
jp.Walk(in, func(path jp.Expr, value any) {
switch v := value.(type) {
case AsMapper:
nativeTypes[path.String()] = v.AsMap()
case uuid.UUID:
nativeTypes[path.String()] = v.String()
case *uuid.UUID:
nativeTypes[path.String()] = v.String()
case time.Duration:
nativeTypes[path.String()] = v
}
})
out := alt.Alter(in, &opts).(map[string]any)
for path, v := range nativeTypes {
expr, err := jp.ParseString(path)
if err != nil {
return nil, err
}
if err := expr.SetOne(out, v); err != nil {
return nil, err
}
}
return out, nil
}