/
config.go
72 lines (57 loc) · 1.45 KB
/
config.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
68
69
70
71
72
package mongo
import (
"fmt"
"github.com/ungerik/go-start/mgo"
)
var Config = Configuration{
Safe: mgo.Safe{FSync: true, J: true},
CheckQuerySelectors: true,
}
var Database *mgo.Database
var collections = map[string]*Collection{}
type Configuration struct {
Host string
Database string
User string
Password string
Safe mgo.Safe
CheckQuerySelectors bool
}
func (self *Configuration) Name() string {
return "mongo"
}
func (self *Configuration) Init() error {
login := ""
if Config.User != "" {
login = Config.User + ":" + Config.Password + "@"
}
host := "localhost"
if Config.Host != "" {
host = Config.Host
}
// http://goneat.org/pkg/github.com/ungerik/go-start/mgo/#Session.Mongo
// [mongodb://][user:pass@]host1[:port1][,host2[:port2],...][/database][?options]
url := fmt.Sprintf("mongodb://%s%s/%s", login, host, Config.Database)
session, err := mgo.Dial(url)
if err != nil {
return err
}
session.SetSafe(&Config.Safe)
Database = session.DB(Config.Database)
for _, collection := range collections {
collection.collection = Database.C(collection.Name)
}
return nil
}
func (self *Configuration) Close() error {
if Database.Session != nil {
Database.Session.Close()
}
return nil
}
func InitLocalhost(database, user, password string) (err error) {
Config.Database = database
Config.User = user
Config.Password = password
return Config.Init()
}