forked from tolsen/mongonet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmongoapi.go
74 lines (67 loc) · 1.67 KB
/
mongoapi.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package mongonet
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/description"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
// RunCommandUsingRawBSON - runs a command using low-level writeWireMessage API
// Notes:
// 1. caller is expected to cleanup mongo.Client object
// 2. Uses primary read preference
// 3. Expects an OP_MSG response back from the server
func RunCommandUsingRawBSON(cmd bson.D, client *mongo.Client, goctx context.Context) (bson.D, error) {
topology := extractTopology(client)
srv, err := topology.SelectServer(goctx, description.ReadPrefSelector(readpref.Primary()))
if err != nil {
return nil, err
}
conn, err := srv.Connection(goctx)
if err != nil {
return nil, err
}
sb, err := SimpleBSONConvert(cmd)
if err != nil {
return nil, err
}
newmsg := &MessageMessage{
MessageHeader{
0,
17,
1,
OP_MSG},
0,
[]MessageMessageSection{
&BodySection{
sb,
},
},
}
if err := conn.WriteWireMessage(goctx, newmsg.Serialize()); err != nil {
return nil, err
}
ret, err := conn.ReadWireMessage(goctx, nil)
if err != nil {
return nil, err
}
resp, err := ReadMessageFromBytes(ret)
if err != nil {
return nil, err
}
if mm, ok := resp.(*MessageMessage); ok {
for _, sec := range mm.Sections {
if bodySection, ok := sec.(*BodySection); ok && bodySection != nil {
respBsonD, err := bodySection.Body.ToBSOND()
if err != nil {
return nil, err
}
return respBsonD, nil
}
}
} else {
return nil, fmt.Errorf("expected an OP_MSG response but got %T", resp)
}
return nil, fmt.Errorf("couldn't find a body section in response")
}