-
Notifications
You must be signed in to change notification settings - Fork 2
/
serializer.go
42 lines (33 loc) · 882 Bytes
/
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
package eventually
import (
"bytes"
"encoding/gob"
"github.com/ahmedkamals/eventually/internal/errors"
)
type (
// Serializer interface
Serializer interface {
serialize(interface{}) ([]byte, error)
deserialize([]byte, interface{}) error
}
serializer struct{}
)
// NewSerializer creates a new Serializer
func NewSerializer() Serializer {
return &serializer{}
}
func (s *serializer) serialize(target interface{}) ([]byte, error) {
const op errors.Operation = "serializer.serialize"
buffer := bytes.Buffer{}
encoder := gob.NewEncoder(&buffer)
if err := encoder.Encode(target); err != nil {
return nil, errors.E(op, errors.Failure, err)
}
return buffer.Bytes(), nil
}
func (s *serializer) deserialize(data []byte, target interface{}) error {
buffer := bytes.Buffer{}
buffer.Write(data)
decoder := gob.NewDecoder(&buffer)
return decoder.Decode(target)
}