1 Star 0 Fork 0

marcello/go-common

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
config.go 1.29 KB
一键复制 编辑 原始数据 按行查看 历史
marcello 提交于 2022-03-18 15:48 +08:00 . replace
package file
import (
"fmt"
"path/filepath"
"strings"
"gitee.com/marcellos/common/config"
"gitee.com/marcellos/common/base"
"gitee.com/marcellos/common/crypto"
"github.com/fsnotify/fsnotify"
"gitee.com/marcellos/common/config/internal"
)
// New 从文件初始化配置
func New(file string, cb func()) (*config.Config, error) {
var (
dir = filepath.Dir(file)
filename = filepath.Base(file)
err error
ok bool
hash, newHash string
)
if ok, err = base.PathExists(file); err != nil || !ok {
return nil, fmt.Errorf("file not exists or no permission")
}
f := strings.Split(filename, ".")
if len(f) != 2 {
return nil, fmt.Errorf("file must contain path, name and suffix; like: /path/to/conf.yaml")
}
if !internal.IsSupportedExt(f[1]) {
return nil, fmt.Errorf("configuration file are not supported")
}
v := config.New()
{
v.SetConfigName(f[0])
v.AddConfigPath(dir)
v.SetConfigType(f[1])
}
if err = v.ReadInConfig(); err != nil {
return nil, err
}
hash, err = crypto.FileMd5(file)
if err != nil {
return nil, err
}
v.WatchConfig()
v.OnConfigChange(func(in fsnotify.Event) {
if newHash, err = crypto.FileMd5(file); err != nil {
return
}
if hash != newHash {
hash = newHash
cb()
}
})
return v, nil
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/marcellos/go-common.git
git@gitee.com:marcellos/go-common.git
marcellos
go-common
go-common
e809a504da49

搜索帮助