/
config.go
83 lines (73 loc) · 1.8 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
73
74
75
76
77
78
79
80
81
82
83
package mongo
import (
"time"
"github.com/henrylee2cn/cfgo"
"gopkg.in/mgo.v2"
)
// Config mongodb setting
type Config struct {
Addrs []string `yaml:"addres"`
Timeout time.Duration `yaml:"timeout"`
Database string `yaml:"database"`
// Username and Password inform the credentials for the initial authentication
// done on the database defined by the Source field. See Session.Login.
Username string `yaml:"username"`
Password string `yaml:"passward"`
// PoolLimit defines the per-server socket pool limit. Defaults to 4096.
// See Session.SetPoolLimit for details.
PoolLimit int `yaml:"pool_limit"`
// NoCache whether to disable cache
NoCache bool `yaml:"no_cache"`
init bool
}
var configs = make(map[string]*Config)
// ReadConfig gets a mongodb db config form yaml.
func ReadConfig(configSection string) (*Config, error) {
conf, ok := configs[configSection]
if ok {
return conf, nil
}
conf = NewConfig()
err := cfgo.Reg(configSection, conf)
if err == nil {
configs[configSection] = conf
return conf, nil
} else {
return nil, err
}
}
// NewConfig creates a default config.
func NewConfig() *Config {
return &Config{
Addrs: []string{"127.0.0.1:27017"},
Timeout: 10,
PoolLimit: 256,
Username: "root",
Password: "",
Database: "test",
}
}
// Reload sync automatically config from config file.
func (cfg *Config) Reload(bind cfgo.BindFunc) error {
if cfg.init {
return nil
}
err := bind()
if err != nil {
return err
}
cfg.init = true
return nil
}
// Set config
func (mgoConfig *Config) Source() *mgo.DialInfo {
dialInfo := &mgo.DialInfo{
Addrs: mgoConfig.Addrs,
Username: mgoConfig.Username,
Password: mgoConfig.Password,
Database: mgoConfig.Database,
Timeout: mgoConfig.Timeout,
PoolLimit: mgoConfig.PoolLimit,
}
return dialInfo
}