-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfactory.go
64 lines (53 loc) · 1.43 KB
/
factory.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
package gomongo
import (
"log"
"time"
mgo "github.com/globalsign/mgo"
)
// Connect ...
func (n MongoDB) Connect(config *Config) (*Connection, error) {
switch config.DbType {
case MONGODB:
conn, err := ConnectMongo(config)
return conn, err
default:
//if type is invalid, return an error
return nil, ErrorInvalidDBType
}
}
// ConnectMongo ...
func ConnectMongo(config *Config) (*Connection, error) {
var mongoDBDialInfo *mgo.DialInfo
var mongoSession *mgo.Session
var err error
if len(config.Uri) > 0 {
mongoSession, err = mgo.Dial(config.Uri)
}else {
mongoDBDialInfo = &mgo.DialInfo{
Addrs: []string{config.Hosts},
Timeout: 60 * time.Second,
Database: config.Database,
ReplicaSetName: config.ReplicaSetName,
Mechanism: "SCRAM-SHA-1",
Source: config.AuthDatabase,
Username: config.Username,
Password: config.Password,
Direct: config.Direct,
}
mongoSession, err = mgo.DialWithInfo(mongoDBDialInfo)
}
if err != nil {
log.Println("connection error : ", err)
return nil, err
}
//mongoSession.SetMode(mgo.Monotonic, true)
// mongoSession.SetSafe(&mgo.Safe{})
mongoSession.SetSafe(&mgo.Safe{WMode: "majority"})
mongoSession.SetPoolLimit(4000)
conn := new(Connection)
conn.Session = mongoSession
conn.Collections = make(map[string]*mgo.Collection)
conn.Session.DB(config.Database)
conn.Database = config.Database
return conn, nil
}