-
Notifications
You must be signed in to change notification settings - Fork 1
/
config-loader.go
55 lines (44 loc) · 991 Bytes
/
config-loader.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
package yamlsvc
import (
"os"
"reflect"
"sync"
"github.com/ahl5esoft/lite-go/contract"
jsoniter "github.com/json-iterator/go"
"gopkg.in/yaml.v3"
)
var configLoaderMutex sync.Mutex
type configLoader struct {
filePath string
doc map[interface{}]interface{}
}
func (m *configLoader) Load(v interface{}) (err error) {
if m.doc == nil {
configLoaderMutex.Lock()
defer configLoaderMutex.Unlock()
if m.doc == nil {
var bf []byte
if bf, err = os.ReadFile(m.filePath); err != nil {
return
}
if err = yaml.Unmarshal(bf, &(m.doc)); err != nil {
return
}
}
}
if cv, ok := m.doc[reflect.TypeOf(v).Elem().Name()]; ok {
var bf []byte
if bf, err = jsoniter.Marshal(cv); err != nil {
return
}
err = jsoniter.Unmarshal(bf, v)
}
return
}
// 创建配置加载器
func NewConfigLoader(osPath contract.IOsPath, yamlName string) contract.IConfigLoader {
wd, _ := os.Getwd()
return &configLoader{
filePath: osPath.Join(wd, yamlName),
}
}