/
context.go
120 lines (96 loc) · 1.87 KB
/
context.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package event
import (
"encoding/json"
"errors"
"strings"
"github.com/fatih/structs"
)
type ContextType string
const (
ContextInvalid ContextType = "invalid"
)
func GetContextType(typ string) ContextType {
for k := range ctxreg {
if strings.EqualFold(typ, string(k)) {
return k
}
}
return ContextInvalid
}
type Context interface {
Type() ContextType
Values() map[string]interface{}
Interface() interface{}
Validate() bool
}
type ContextValidator interface {
Validate() bool
}
type context struct {
typ ContextType
v interface{}
}
func NewContext(typ ContextType, v interface{}) Context {
return &context{
typ: typ,
v: v,
}
}
func (ctx context) Type() ContextType {
return ctx.typ
}
func (ctx context) Values() map[string]interface{} {
if structs.IsStruct(ctx.v) {
s := structs.New(ctx.v)
s.TagName = "json"
return s.Map()
}
switch vv := ctx.v.(type) {
case map[string]interface{}:
return vv
case map[string]string:
m := make(map[string]interface{}, len(vv))
for k, v := range vv {
m[k] = v
}
return m
default:
return map[string]interface{}{}
}
}
func (ctx *context) Interface() interface{} {
return ctx.v
}
func (ctx *context) Validate() bool {
v, ok := ctx.v.(ContextValidator)
if ok {
return v.Validate()
}
return true
}
func emptyContext(typ ContextType) (Context, error) {
ctor, ok := ctxreg[typ]
if !ok {
return nil, errors.New("context type unknown")
}
return ctor(), nil
}
func decodeContext(typ string, vals json.RawMessage) (Context, error) {
ct := GetContextType(typ)
if ct == ContextInvalid {
return nil, errors.New("context type invalid")
}
ec, err := emptyContext(ct)
if err != nil {
return nil, err
}
nv := ec.Interface()
if err := json.Unmarshal(vals, &nv); err != nil {
return nil, err
}
ctx, ok := nv.(Context)
if !ok {
return nil, errors.New("invalid context")
}
return ctx, nil
}