-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
67 lines (54 loc) · 1.38 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
64
65
66
67
package app
import (
"os"
"strings"
log "github.com/Sirupsen/logrus"
"labix.org/v2/mgo"
)
const (
defaultURI = "mongodb://dockerhost:27017/soccerscore"
)
var (
ses *mgo.Session
)
func getDbURI() string {
if mgoURI := os.Getenv("MONGODB_URI"); mgoURI != "" {
return mgoURI
}
return defaultURI
}
// getDbName extracts database name from MongoDB URI (e.g. mongodb://localhost/test?replicaSet=test),
// see http://docs.mongodb.org/manual/reference/connection-string/.
func getDbName() string {
uriParts := strings.SplitN(getDbURI(), "/", 4)
// get the last part (maybe a name with or without options)
name := uriParts[len(uriParts)-1]
// get the first part of name (omit options if any)
nameParts := strings.SplitN(name, "?", 2)
return nameParts[0]
}
//Session get session from mongodb
func Session() (*mgo.Session, error) {
var err error
if ses == nil {
mgoURI := getDbURI()
log.Println(mgoURI)
if ses, err = mgo.Dial(mgoURI); err != nil {
log.Fatal("can't connect to mongo:", err)
return nil, err
}
// sets mongodb mode
ses.SetMode(mgo.Monotonic, true)
// sets mongodb safety mode
ses.SetSafe(&mgo.Safe{})
}
return ses.Copy(), nil
}
//DB get specific collection
func DB(ses *mgo.Session) *mgo.Database {
return ses.DB(getDbName())
}
//LeagueMappers get sites collection
func LeagueMappers(ses *mgo.Session) *mgo.Collection {
return DB(ses).C("league_mappers")
}