-
Notifications
You must be signed in to change notification settings - Fork 6
/
bson.go
55 lines (47 loc) · 1.17 KB
/
bson.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
54
55
package dstruct
import (
"fmt"
"reflect"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/bsoncodec"
"go.mongodb.org/mongo-driver/bson/bsonrw"
"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
)
func (d *DStruct) UnmarshalBSON(data []byte) error {
d.init()
elems, err := bsoncore.Document(data).Elements()
if err != nil {
return err
}
for _, elem := range elems {
field := elem.Key()
rawTye, ok := d.fields[field]
if !ok {
continue
}
dc := bsoncodec.DecodeContext{Registry: bson.DefaultRegistry}
vr := bsonrw.NewBSONValueReader(elem.Value().Type, elem.Value().Data)
decoder, err := bson.NewDecoderWithContext(dc, vr)
if err != nil {
return err
}
val := reflect.New(rawTye)
if err = decoder.Decode(val.Interface()); err != nil {
return err
}
if val.IsNil() {
d.kv[field] = val.Elem()
continue
}
d.kv[field] = val.Elem().Interface()
if d.validate != nil {
if err := d.validate(val.Elem()); err != nil {
return fmt.Errorf("validator: field(" + field + ") type(" + rawTye.Name() + ") " + err.Error())
}
}
}
return nil
}
func (d *DStruct) MarshalBSON() ([]byte, error) {
return bson.Marshal(d.kv)
}