-
Notifications
You must be signed in to change notification settings - Fork 0
/
serial.go
45 lines (36 loc) · 942 Bytes
/
serial.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
package gfserial
import (
"bytes"
"encoding/gob"
"encoding/json"
)
// Serializable 接口函数
type Serializable interface {
Serialize() ([]byte, error)
Deserialize([]byte) error
}
// Serializer 接口函数
type Serializer interface {
Serialize(val interface{}) ([]byte, error)
Deserialize(raw []byte, val interface{}) error
}
type JsonSerializer struct{}
func (JsonSerializer) Serialize(val interface{}) ([]byte, error) {
return json.Marshal(val)
}
func (JsonSerializer) Deserialize(raw []byte, val interface{}) error {
return json.Unmarshal(raw, val)
}
type GobSerializer struct{}
func (GobSerializer) Serialize(val interface{}) ([]byte, error) {
buff := &bytes.Buffer{}
enc := gob.NewEncoder(buff)
err := enc.Encode(val)
return buff.Bytes(), err
}
func (GobSerializer) Deserialize(raw []byte, val interface{}) error {
buff := bytes.NewReader(raw)
dec := gob.NewDecoder(buff)
err := dec.Decode(val)
return err
}