...
1
2
3
4
5
6
7 package codecutil
8
9 import (
10 "bytes"
11 "errors"
12 "fmt"
13 "io"
14 "reflect"
15
16 "go.mongodb.org/mongo-driver/bson"
17 "go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
18 )
19
20 var ErrNilValue = errors.New("value is nil")
21
22
23
24 type MarshalError struct {
25 Value interface{}
26 Err error
27 }
28
29
30 func (e MarshalError) Error() string {
31 return fmt.Sprintf("cannot transform type %s to a BSON Document: %v",
32 reflect.TypeOf(e.Value), e.Err)
33 }
34
35
36 type EncoderFn func(io.Writer) (*bson.Encoder, error)
37
38
39
40 func MarshalValue(val interface{}, encFn EncoderFn) (bsoncore.Value, error) {
41
42 if bval, ok := val.(bsoncore.Value); ok {
43 return bval, nil
44 }
45
46 if val == nil {
47 return bsoncore.Value{}, ErrNilValue
48 }
49
50 buf := new(bytes.Buffer)
51
52 enc, err := encFn(buf)
53 if err != nil {
54 return bsoncore.Value{}, err
55 }
56
57
58
59 err = enc.Encode(bson.D{{Key: "", Value: val}})
60 if err != nil {
61 return bsoncore.Value{}, MarshalError{Value: val, Err: err}
62 }
63
64 return bsoncore.Document(buf.Bytes()).Index(0).Value(), nil
65 }
66
View as plain text