-
Notifications
You must be signed in to change notification settings - Fork 1
/
json_decoder.go
47 lines (41 loc) · 1.07 KB
/
json_decoder.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
package decoder
import (
"encoding/json"
"github.com/licheng1013/rocket-cat/common"
"github.com/licheng1013/rocket-cat/messages"
)
type JsonDecoder struct {
}
// EncodeBytes 编码为字节
func (d JsonDecoder) Encode(result interface{}) []byte {
switch result.(type) {
case []byte:
return result.([]byte)
}
bytes, err := json.Marshal(result)
if err != nil {
common.CatLog.Println("JsonDecoder -> 转换失败")
return []byte{}
}
return bytes
}
// DecoderBytes 处理客户端返回的数据
func (d JsonDecoder) Decoder(bytes []byte) messages.Message {
msg := messages.JsonMessage{}
err := json.Unmarshal(bytes, &msg)
if err != nil {
common.CatLog.Println("JsonDecoder -> 解析失败")
}
return &msg
}
// Tool 工具方法
func (d JsonDecoder) Data(cmd, subCmd int64, body interface{}) []byte {
message := messages.JsonMessage{Merge: common.CmdKit.GetMerge(cmd, subCmd)}
message.SetBody(body)
return d.Encode(&message)
}
// JsonDecoderBytes 工具方法
func JsonDecoderBytes(bytes []byte) messages.Message {
j := &JsonDecoder{}
return j.Decoder(bytes)
}