-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdb.go
53 lines (41 loc) · 1017 Bytes
/
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
package main
import (
"fmt"
"labix.org/v2/mgo"
)
const (
DATABASE = "cpbr8app"
)
var conn *MongoConnection
func init() {
conn = new(MongoConnection)
}
// Returns the current global connection object
func GetMongoConnection() *MongoConnection {
return conn
}
// Returns a the project database and the current session
func GetDatabase() (*mgo.Database, *mgo.Session) {
s := conn.session.Copy()
return s.DB(DATABASE), s
}
// Stores the global mongo session
type MongoConnection struct {
session *mgo.Session
}
// Connect to the dabase with given user and password and store the session
func (m *MongoConnection) Connect(user string, password string) {
uri := fmt.Sprintf("mongodb://%s:%[email protected]:31711/%s",
user, password, DATABASE)
session, err := mgo.Dial(uri)
if err != nil {
fmt.Println("Authentication failed!")
panic(err)
}
session.SetMode(mgo.Monotonic, true)
m.session = session
}
// Close the stored session
func (m *MongoConnection) Close() {
m.session.Close()
}