-
Notifications
You must be signed in to change notification settings - Fork 2
/
serializer.go
53 lines (43 loc) · 1.11 KB
/
serializer.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
package flyrpc
import (
"encoding/json"
"reflect"
)
type Message interface{}
var (
typeBytes = reflect.TypeOf([]byte{})
typeString = reflect.TypeOf("")
)
func MessageToBytes(message Message, serializer Serializer) ([]byte, error) {
messageType := reflect.TypeOf(message)
if messageType == typeBytes {
return message.([]byte), nil
}
if messageType == typeString {
return []byte(message.(string)), nil
}
return serializer.Marshal(message)
}
type Serializer interface {
Marshal(interface{}) ([]byte, error)
Unmarshal([]byte, interface{}) error
}
type serializer struct {
marshal func(interface{}) ([]byte, error)
unmarshal func([]byte, interface{}) error
}
func NewSerializer(marshal func(interface{}) ([]byte, error), unmarshal func([]byte, interface{}) error) Serializer {
return &serializer{
marshal: marshal,
unmarshal: unmarshal,
}
}
func (s *serializer) Marshal(msg interface{}) ([]byte, error) {
return s.marshal(msg)
}
func (s *serializer) Unmarshal(bytes []byte, msg interface{}) error {
return s.unmarshal(bytes, msg)
}
var (
JSON Serializer = NewSerializer(json.Marshal, json.Unmarshal)
)