-
Notifications
You must be signed in to change notification settings - Fork 21
/
serialization.go
48 lines (40 loc) · 1.13 KB
/
serialization.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
package relay
import (
"encoding/gob"
"encoding/json"
"io"
)
// Serializer interface is used to encode and
// decode messages. If not provided, a default serializer
// using gob is provided.
type Serializer interface {
ContentType() string
RelayEncode(io.Writer, interface{}) error
RelayDecode(io.Reader, interface{}) error
}
// GOBSerializer implements the Serializer interface and uses the GOB format
type GOBSerializer struct{}
func (*GOBSerializer) ContentType() string {
return "binary/gob"
}
func (*GOBSerializer) RelayEncode(w io.Writer, e interface{}) error {
enc := gob.NewEncoder(w)
return enc.Encode(e)
}
func (*GOBSerializer) RelayDecode(r io.Reader, o interface{}) error {
dec := gob.NewDecoder(r)
return dec.Decode(o)
}
// JSONSerializer implements the Serializer interface and uses JSON
type JSONSerializer struct{}
func (*JSONSerializer) ContentType() string {
return "text/json"
}
func (*JSONSerializer) RelayEncode(w io.Writer, e interface{}) error {
enc := json.NewEncoder(w)
return enc.Encode(e)
}
func (*JSONSerializer) RelayDecode(r io.Reader, o interface{}) error {
dec := json.NewDecoder(r)
return dec.Decode(o)
}