/
formats.go
53 lines (45 loc) · 1.5 KB
/
formats.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 registry
import (
"encoding/json"
"github.com/mongodb/amboy"
"github.com/pkg/errors"
"go.mongodb.org/mongo-driver/bson"
mgobson "gopkg.in/mgo.v2/bson"
)
// ConvertTo takes a Format specification and interface and returns a
// serialized byte sequence according to that Format value. If there
// is an issue with the serialization, or the Format value is not
// supported, then this method returns an error.
func convertTo(f amboy.Format, v interface{}) ([]byte, error) {
var output []byte
var err error
switch f {
case amboy.JSON:
output, err = json.Marshal(v)
case amboy.BSON:
output, err = mgobson.Marshal(v)
case amboy.BSON2:
output, err = bson.Marshal(v)
default:
return nil, errors.New("no support for specified serialization format")
}
if err != nil {
return nil, errors.Wrap(err, "problem serializing data")
}
return output, nil
}
// ConvertFrom takes a Format type, a byte sequence, and an interface
// and attempts to deserialize that data into the interface object as
// indicated by the Format specifier.
func convertFrom(f amboy.Format, data []byte, v interface{}) error {
switch f {
case amboy.JSON:
return errors.Wrap(json.Unmarshal(data, v), "problem serializing data from json")
case amboy.BSON:
return errors.Wrap(mgobson.Unmarshal(data, v), "problem serializing data from bson")
case amboy.BSON2:
return errors.Wrap(bson.Unmarshal(data, v), "problem serializing data from bson (new)")
default:
return errors.New("no support for specified serialization format")
}
}