-
Notifications
You must be signed in to change notification settings - Fork 1
/
configuration.go
96 lines (79 loc) · 1.64 KB
/
configuration.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
84
85
86
87
88
89
90
91
92
93
94
95
96
// author: wsfuyibing <[email protected]>
// date: 2023-02-18
package db
import (
_ "github.com/go-sql-driver/mysql"
"gopkg.in/yaml.v3"
"os"
"sync"
)
var (
// Config
// 应用于IRIS的配置.
Config *Configuration
)
type (
// Configuration
// 配置参数.
Configuration struct {
// 数据源列表.
Databases map[string]*Database `yaml:"databases"`
mu sync.RWMutex
undefinedDatabase *Database
}
)
// GetDatabase
// 按Key名称读取数据源.
func (o *Configuration) GetDatabase(key string) *Database {
o.mu.RLock()
defer o.mu.RUnlock()
if database, ok := o.Databases[key]; ok {
return database
}
return nil
}
// GetUndefined
// 读取数据源.
func (o *Configuration) GetUndefined() *Database {
o.mu.RLock()
defer o.mu.RUnlock()
return o.undefinedDatabase
}
// SetDatabase
// 设置数据源.
func (o *Configuration) SetDatabase(key string, database *Database) {
o.mu.Lock()
defer o.mu.Unlock()
if database == nil {
delete(o.Databases, key)
} else {
o.Databases[key] = database.init()
}
}
func (o *Configuration) defaults() {
if o.Databases == nil {
o.Databases = make(map[string]*Database)
}
for _, v := range o.Databases {
v.init()
}
}
func (o *Configuration) init() *Configuration {
o.mu = sync.RWMutex{}
o.scan()
o.defaults()
o.undefinedDatabase = (&Database{
Dsn: []string{defaultEngineDsn},
internal: true,
}).init()
return o
}
func (o *Configuration) scan() {
for _, f := range []string{"./tmp/db.yaml", "./config/db.yaml", "../tmp/db.yaml", "../config/db.yaml"} {
if body, err := os.ReadFile(f); err == nil {
if yaml.Unmarshal(body, o) == nil {
return
}
}
}
}