/
encoding.go
50 lines (45 loc) · 993 Bytes
/
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
package broker
import (
"bytes"
"encoding/gob"
"errors"
"github.com/devexps/go-micro/v2/encoding"
_ "github.com/devexps/go-micro/v2/encoding/json"
_ "github.com/devexps/go-micro/v2/encoding/proto"
)
func Marshal(codec encoding.Codec, msg Any) ([]byte, error) {
if msg == nil {
return nil, errors.New("message is nil")
}
if codec != nil {
dataBuffer, err := codec.Marshal(msg)
if err != nil {
return nil, err
}
return dataBuffer, nil
} else {
switch t := msg.(type) {
case []byte:
return t, nil
case string:
return []byte(t), nil
default:
var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
if err := enc.Encode(msg); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
}
}
func Unmarshal(codec encoding.Codec, inputData []byte, outValue interface{}) error {
if codec != nil {
if err := codec.Unmarshal(inputData, outValue); err != nil {
return err
}
} else if outValue == nil {
outValue = inputData
}
return nil
}