-
Notifications
You must be signed in to change notification settings - Fork 5
/
route_data.go
101 lines (84 loc) · 1.79 KB
/
route_data.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
package fir
import (
"errors"
"fmt"
"reflect"
"github.com/goccy/go-json"
"github.com/fatih/structs"
)
type routeData map[string]any
func (r *routeData) Error() string {
b, _ := json.Marshal(r)
return string(b)
}
type stateData map[string]any
func (r *stateData) Error() string {
b, _ := json.Marshal(r)
return string(b)
}
type routeDataWithState struct {
routeData *routeData
stateData *stateData
}
func (r *routeDataWithState) Error() string {
b1, _ := json.Marshal(r.routeData)
b2, _ := json.Marshal(r.stateData)
return fmt.Sprintf("routeData: %s\n stateData: %s", string(b1), string(b2))
}
func buildData(stateOnly bool, dataset ...any) error {
if len(dataset) == 0 {
return nil
}
m := make(map[string]any)
hasState := false
state := make(stateData)
for _, data := range dataset {
if data == nil {
continue
}
if sv, ok := data.(*stateData); ok {
hasState = true
for k, v := range *sv {
state[k] = v
m[k] = v
}
}
val := reflect.ValueOf(data)
if val.Kind() == reflect.Ptr {
el := val.Elem() // dereference the pointer
if el.Kind() == reflect.Struct {
for k, v := range structs.Map(data) {
m[k] = v
}
}
} else if val.Kind() == reflect.Struct {
for k, v := range structs.Map(data) {
m[k] = v
}
} else if val.Kind() == reflect.Map {
ms, ok := data.(map[string]any)
if !ok {
return errors.New("data must be a map[string]any , struct or pointer to a struct")
}
for k, v := range ms {
m[k] = v
}
} else {
return errors.New("data must be a map[string]any , struct or pointer to a struct")
}
}
if stateOnly {
t := stateData(m)
return &t
}
if hasState {
r := routeData(m)
t := routeDataWithState{
routeData: &r,
stateData: &state,
}
return &t
}
r := routeData(m)
return &r
}