/
encoding.go
123 lines (99 loc) · 2.28 KB
/
encoding.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
121
122
123
package mns
import (
"encoding/xml"
"errors"
"io"
"reflect"
"github.com/gogap/ali_mns"
"github.com/gogap/spirit"
)
var _ spirit.Component = new(MNSEncodingComponent)
const (
mnsEncodingURN = "urn:spirit-contrib:component:encoding:mns"
)
var (
ErrDataTypeIsNotStruct = errors.New("payload data type is not a struct")
ErrDataTypeCouldNotBeDecode = errors.New("payload data type could not be decode")
)
type MNSEncodingComponentConfig struct {
SingleMessage bool `json:"single_message"`
}
type MNSEncodingComponent struct {
conf MNSEncodingComponentConfig
}
func init() {
spirit.RegisterComponent(mnsEncodingURN, NewMNSEncodingComponent)
}
func NewMNSEncodingComponent(config spirit.Map) (component spirit.Component, err error) {
conf := MNSEncodingComponentConfig{}
if err = config.ToObject(&conf); err != nil {
return
}
component = &MNSEncodingComponent{conf: conf}
return
}
func (p *MNSEncodingComponent) URN() string {
return mnsEncodingURN
}
func (p *MNSEncodingComponent) Labels() spirit.Labels {
return spirit.Labels{
"version": "0.0.1",
}
}
func (p *MNSEncodingComponent) Handlers() spirit.Handlers {
return spirit.Handlers{
"encode": p.Encode,
"decode": p.Decode,
}
}
func (p *MNSEncodingComponent) Encode(payload spirit.Payload) (result interface{}, err error) {
var vData interface{}
if vData, err = payload.GetData(); err != nil {
return
}
dataKind := reflect.TypeOf(vData).Kind()
if dataKind == reflect.Ptr ||
dataKind == reflect.Struct {
var data []byte
data, result = xml.Marshal(vData)
result = data
} else {
err = ErrDataTypeIsNotStruct
return
}
return
}
func (p *MNSEncodingComponent) Decode(payload spirit.Payload) (result interface{}, err error) {
var vData interface{}
if vData, err = payload.GetData(); err != nil {
return
}
var resp interface{}
if p.conf.SingleMessage {
resp = &ali_mns.MessageReceiveResponse{}
} else {
resp = &ali_mns.BatchMessageReceiveResponse{}
}
switch data := vData.(type) {
case string:
{
err = xml.Unmarshal([]byte(data), &resp)
}
case []byte:
{
err = xml.Unmarshal(data, &resp)
}
case io.Reader:
{
reader := xml.NewDecoder(data)
err = reader.Decode(&resp)
}
default:
err = ErrDataTypeCouldNotBeDecode
return
}
if err == nil {
result = resp
}
return
}