-
Notifications
You must be signed in to change notification settings - Fork 3
/
connection.go
57 lines (47 loc) · 1.16 KB
/
connection.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
package mgobench
import (
"errors"
"strings"
"gopkg.in/mgo.v2"
)
// IsBlankString return if string is only space or empty / zero length
func IsBlankString(s string) bool {
return strings.TrimSpace(s) == ""
}
type CollectionBindFunc func(s *mgo.Session) (*mgo.Collection, error)
func NewCollectionBindFunc(db string, coll string) CollectionBindFunc {
if IsBlankString(db) || IsBlankString(coll) {
return nil
}
return func(s *mgo.Session) (*mgo.Collection, error) {
if s == nil {
return nil, errors.New("nil session")
}
sc := s.Copy()
// fmt.Printf("Database ---- %s \n Collection ---- %s \n", db, coll)
return sc.DB(db).C(coll), nil
}
}
type MgoManager struct {
Session *mgo.Session
CFn CollectionBindFunc
}
func (mc MgoManager) Coll() (*mgo.Collection, error) {
if mc.Session == nil {
panic("nil mgo session")
}
if mc.CFn == nil {
return nil, errors.New("CollectionBindFunc 'CFn' is nil")
}
return mc.CFn(mc.Session)
}
func NewMgoManagerWithDefaultBinder(s *mgo.Session, db string, coll string) *MgoManager {
cfn := NewCollectionBindFunc(db, coll)
if cfn == nil {
return nil
}
return &MgoManager{
Session: s,
CFn: cfn,
}
}