-
Notifications
You must be signed in to change notification settings - Fork 1
/
message_option.go
79 lines (66 loc) · 1.25 KB
/
message_option.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
package mqtt
import (
`github.com/goexl/mengpo`
`github.com/goexl/xiren`
)
type (
messageOption interface {
applyMessage(options *messageOptions)
}
messageOptions struct {
serializer serializer
defaults bool
validates bool
}
)
func (m *messageOptions) marshal(from interface{}) (to []byte, err error) {
// 加载默认值
if m.defaults {
err = mengpo.Set(from)
}
if nil != err {
return
}
// 数据验证
if m.validates {
err = xiren.Struct(from)
}
if nil != err {
return
}
// 序列化
to, err = m.serializer.Marshal(from)
return
}
func (m *messageOptions) unmarshal(bytes []byte, from interface{}) (err error) {
// 反序列化
if err = m.serializer.Unmarshal(bytes, from); nil != err {
return
}
// 加载默认值
if m.defaults {
err = mengpo.Set(from)
}
if nil != err {
return
}
// 数据验证
if m.validates {
err = xiren.Struct(from)
}
return
}
func newMessageOptions(mqtt mqttOptions) *messageOptions {
return &messageOptions{
serializer: mqtt.Serializer,
defaults: mqtt.Defaults && mqtt.Default,
validates: mqtt.Validates && mqtt.Validate,
}
}
func defaultMessageOptions() *messageOptions {
return &messageOptions{
serializer: serializerJson,
defaults: true,
validates: true,
}
}