-
Notifications
You must be signed in to change notification settings - Fork 21
/
db.go
63 lines (55 loc) · 1.23 KB
/
db.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
// Package db to connect to mongodb
package db
import (
"errors"
"fmt"
"github.com/MG-RAST/AWE/lib/conf"
mgo "gopkg.in/mgo.v2"
"time"
)
const (
DialTimeout = time.Duration(time.Second * 10)
DialAttempts = 3
)
var (
Connection connection
DbTimeout = time.Second * time.Duration(conf.MONGODB_TIMEOUT)
)
type connection struct {
dbname string
username string
password string
Session *mgo.Session
DB *mgo.Database
}
func Initialize() (err error) {
c := connection{}
// test connection
canDial := false
for i := 0; i < DialAttempts; i++ {
s, err := mgo.DialWithTimeout(conf.MONGODB_HOST, DialTimeout)
if err == nil {
s.Close()
canDial = true
break
}
}
if !canDial {
return errors.New(fmt.Sprintf("no reachable mongodb server(s) at %s", conf.MONGODB_HOST))
}
// get handle
s, err := mgo.DialWithTimeout(conf.MONGODB_HOST, DbTimeout)
if err != nil {
return errors.New(fmt.Sprintf("no reachable mongodb server(s) at %s", conf.MONGODB_HOST))
}
c.Session = s
c.DB = c.Session.DB(conf.MONGODB_DATABASE)
if conf.MONGODB_USER != "" && conf.MONGODB_PASSWD != "" {
c.DB.Login(conf.MONGODB_USER, conf.MONGODB_PASSWD)
}
Connection = c
return
}
func Drop() error {
return Connection.DB.DropDatabase()
}