-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathserializers.go
More file actions
56 lines (45 loc) · 1.45 KB
/
serializers.go
File metadata and controls
56 lines (45 loc) · 1.45 KB
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
54
55
56
package securebytes
import (
"bytes"
"encoding/asn1"
"encoding/gob"
"encoding/json"
)
// Serializer is an interface which allows to choose between GOBSerializer and JSONSerializer
type Serializer interface {
Marshal(interface{}) ([]byte, error)
Unmarshal([]byte, interface{}) error
}
// GOBSerializer uses encoding/gob to encode and decode data
type GOBSerializer struct{}
// Marshal data with gob serializer
func (g GOBSerializer) Marshal(v interface{}) ([]byte, error) {
var buf bytes.Buffer
err := gob.NewEncoder(&buf).Encode(v)
return buf.Bytes(), err
}
// Unmarshal data with gob serializer
func (g GOBSerializer) Unmarshal(data []byte, v interface{}) error {
return gob.NewDecoder(bytes.NewReader(data)).Decode(v)
}
// JSONSerializer uses encoding/json to encode and decode data
type JSONSerializer struct{}
// Marshal data with json serializer
func (j JSONSerializer) Marshal(v interface{}) ([]byte, error) {
return json.Marshal(v)
}
// Unmarshal data with json serializer
func (j JSONSerializer) Unmarshal(data []byte, v interface{}) error {
return json.Unmarshal(data, v)
}
// ASN1Serializer uses encoding/asn1 to encode and decode data
type ASN1Serializer struct{}
// Marshal data with asn1 serializer
func (a ASN1Serializer) Marshal(v interface{}) ([]byte, error) {
return asn1.Marshal(v)
}
// Unmarshal data with asn1 serializer
func (a ASN1Serializer) Unmarshal(data []byte, v interface{}) error {
_, err := asn1.Unmarshal(data, v)
return err
}