Skip to content

Commit 720800d

Browse files
committed
fix
1 parent a02c34e commit 720800d

File tree

13 files changed

+106
-208
lines changed

13 files changed

+106
-208
lines changed

config/abc.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,10 @@ func (t CfgMap) GetString(name string) string {
2222
return ""
2323
}
2424

25+
type DecoderOption = viper.DecoderConfigOption
2526
type Config interface {
2627
LoadPath(path string)
27-
LoadEnv(names ...string)
28-
UnmarshalKey(key string, rawVal interface{}, opts ...viper.DecoderConfigOption) error
28+
UnmarshalKey(key string, rawVal interface{}, opts ...DecoderOption) error
2929
Decode(name string, cfgMap interface{}) error
3030
Get(key string) interface{}
3131
Set(string, interface{})
File renamed without changes.

config/builder.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,16 @@ package config
22

33
import (
44
"github.com/pubgo/dix"
5-
"github.com/pubgo/xerror"
5+
"github.com/pubgo/funk"
66
)
77

88
func init() {
9+
defer funk.RecoverAndExit()
910
dix.Provider(func() Config { return newCfg() })
1011
dix.Provider(func(c Config) *App {
1112
var cfg App
12-
xerror.Panic(c.UnmarshalKey("app", &cfg))
13-
xerror.Panic(cfg.Check())
13+
funk.Must(c.UnmarshalKey("app", &cfg))
14+
funk.Must(cfg.Check())
1415
return &cfg
1516
})
1617
}

config/builder_test.go

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,19 @@
11
package config
22

33
import (
4-
"github.com/pubgo/lava/internal/pkg/env"
54
"testing"
65

7-
"github.com/smartystreets/assertions"
8-
"github.com/smartystreets/assertions/should"
6+
"github.com/pubgo/lava/internal/pkg/env"
7+
8+
"github.com/stretchr/testify/assert"
99
)
1010

1111
func TestName(t *testing.T) {
12-
var assert = assertions.New(t)
12+
var is = assert.New(t)
1313

14-
env.Set("env_prefix", "hello")
15-
env.Set("hello_123", "app.name=hello")
14+
env.Set("lava_hello", "hello")
1615

1716
var c = newCfg()
18-
assert.So(c, should.NotBeNil)
19-
assert.So(c.GetString("app.name"), should.Equal, "hello")
20-
assert.So(c.GetString("app.home"), should.Equal, c.GetString("app.project"))
17+
is.NotNil(c)
18+
is.Equal(c.GetString("hello"), "hello")
2119
}

config/config.go

Lines changed: 39 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,14 @@ package config
33
import (
44
"fmt"
55
"io"
6+
"io/fs"
67
"path/filepath"
78
"reflect"
89
"strings"
910
"sync"
1011

1112
"github.com/mitchellh/mapstructure"
13+
"github.com/pubgo/funk"
1214
"github.com/pubgo/x/iox"
1315
"github.com/pubgo/x/pathutil"
1416
"github.com/pubgo/xerror"
@@ -25,10 +27,11 @@ import (
2527
)
2628

2729
var (
28-
CfgType = "yaml"
29-
CfgName = "config"
30-
CfgDir = env.Get("cfg_dir", "app_cfg_dir")
31-
CfgPath = filepath.Join("configs", "config", "config.yaml")
30+
CfgType = "yaml"
31+
CfgName = "config"
32+
CfgDir = env.Get("app_cfg_home", "project_cfg_home", consts.EnvCfgHome)
33+
CfgPath = filepath.Join("configs", "config", "config.yaml")
34+
EnvPrefix = utils.FirstNotEmpty(env.Get("cfg_env_prefix", "app_env_prefix", "project_env_prefix", consts.EnvCfgPrefix), "lava")
3235
)
3336

3437
// Init 处理所有的配置,环境变量和flag
@@ -37,8 +40,6 @@ var (
3740
// flag可以指定配置文件位置
3841
// 始化配置文件
3942
func newCfg() *configImpl {
40-
defer xerror.RecoverAndExit()
41-
4243
var t = &configImpl{v: viper.New()}
4344
// 配置处理
4445
v := t.v
@@ -47,40 +48,52 @@ func newCfg() *configImpl {
4748
v.SetConfigType(CfgType)
4849
v.SetConfigName(CfgName)
4950
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_", "-", "_"))
50-
prefix := utils.FirstNotEmpty(env.Get("cfg_env_prefix", "env_prefix"), "lava")
51-
v.SetEnvPrefix(prefix)
51+
v.SetEnvPrefix(strings.ToUpper(EnvPrefix))
5252
v.AutomaticEnv()
5353

5454
// 初始化框架, 加载环境变量, 加载本地配置
5555
// 初始化完毕所有的配置以及外部配置以及相关的参数和变量
5656
// 然后获取配置了
5757
xerror.PanicF(t.initCfg(v), "config file load error")
58-
t.LoadEnv()
59-
6058
CfgPath = v.ConfigFileUsed()
6159
CfgDir = filepath.Dir(filepath.Dir(v.ConfigFileUsed()))
62-
xerror.Panic(env.Set(consts.EnvCfgDir, CfgDir))
60+
xerror.Panic(env.Set(consts.EnvCfgHome, CfgDir))
61+
t.LoadPath(CfgPath)
6362

6463
// 加载自定义配置
65-
//t.LoadPath(customCfgPath(app.Mode.String()))
66-
//t.LoadPath(customCfgPath(app.Project))
64+
t.loadCustomCfg()
6765
return t
6866
}
6967

70-
func customCfgPath(name string) string {
71-
return filepath.Join(filepath.Dir(CfgPath), fmt.Sprintf("%s.%s.%s", CfgName, name, CfgType))
72-
}
73-
7468
var _ Config = (*configImpl)(nil)
7569

7670
type configImpl struct {
7771
rw sync.RWMutex
7872
v *viper.Viper
7973
}
8074

81-
func (t *configImpl) LoadEnv(names ...string) {
82-
names = append(names, "cfg_env_prefix", "env_prefix")
83-
loadEnvFromPrefix(env.Get(names...), t.v)
75+
func (t *configImpl) loadCustomCfg() {
76+
var path = filepath.Dir(t.v.ConfigFileUsed())
77+
funk.MustMsg(filepath.Walk(path, func(path string, info fs.FileInfo, err error) error {
78+
if err != nil {
79+
return err
80+
}
81+
82+
if info.IsDir() {
83+
return nil
84+
}
85+
86+
if !strings.HasSuffix(info.Name(), "."+CfgType) {
87+
return nil
88+
}
89+
90+
if info.Name() == CfgName+"."+CfgType {
91+
return nil
92+
}
93+
94+
t.LoadPath(path)
95+
return nil
96+
}), "walk path failed, path=%s", path)
8497
}
8598

8699
func (t *configImpl) All() map[string]interface{} {
@@ -205,17 +218,17 @@ func (t *configImpl) initWithDir(v *viper.Viper) bool {
205218
return false
206219
}
207220

208-
xerror.Assert(pathutil.IsNotExist(CfgDir), "config dir not found, path:%s", CfgPath)
221+
funk.Assert(pathutil.IsNotExist(CfgDir), "config dir not found, path:%s", CfgPath)
209222
v.AddConfigPath(filepath.Join(CfgDir, CfgName))
210-
xerror.PanicF(v.ReadInConfig(), "config load error, dir:%s", CfgDir)
223+
funk.MustMsg(v.ReadInConfig(), "config load error, dir:%s", CfgDir)
211224

212225
return true
213226
}
214227

215228
func (t *configImpl) initCfg(v *viper.Viper) (err error) {
216229
defer xerror.RecoverErr(&err)
217230

218-
// 指定配置文件目录
231+
// 指定配置目录
219232
if t.initWithDir(v) {
220233
return
221234
}
@@ -226,7 +239,7 @@ func (t *configImpl) initCfg(v *viper.Viper) (err error) {
226239
}
227240

228241
var pathList = strMap(getPathList(), func(str string) string { return filepath.Join(str, "configs", CfgName) })
229-
xerror.Assert(len(pathList) == 0, "pathList is zero")
242+
xerror.Assert(len(pathList) == 0, "config path not found")
230243

231244
for i := range pathList {
232245
if t.addConfigPath(pathList[i]) {
@@ -243,6 +256,8 @@ func (t *configImpl) LoadPath(path string) {
243256
return
244257
}
245258

259+
fmt.Printf("load config %s\n", path)
260+
246261
tmp, err := fasttemplate.NewTemplate(xerror.PanicStr(iox.ReadText(path)), "{{", "}}")
247262
xerror.Panic(err, "unexpected error when parsing template")
248263

@@ -256,5 +271,4 @@ func (t *configImpl) LoadPath(path string) {
256271

257272
return w.Write([]byte(t.v.GetString(tag)))
258273
}))))
259-
t.LoadEnv()
260274
}

config/util.go

Lines changed: 2 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,10 @@ package config
22

33
import (
44
"fmt"
5+
"github.com/pubgo/lava/consts"
6+
"github.com/pubgo/xerror"
57
"os"
68
"path/filepath"
7-
"strings"
8-
9-
"github.com/iancoleman/strcase"
10-
"github.com/pubgo/xerror"
11-
"github.com/spf13/viper"
12-
13-
"github.com/pubgo/lava/consts"
14-
"github.com/pubgo/lava/internal/pkg/env"
159
)
1610

1711
const pkgKey = "name"
@@ -51,28 +45,6 @@ func strMap(strList []string, fn func(str string) string) []string {
5145
return strList
5246
}
5347

54-
func loadEnvFromPrefix(envPrefix string, v *viper.Viper) {
55-
if envPrefix == "" {
56-
return
57-
}
58-
59-
var r = strings.NewReplacer("-", "_", ".", "_", "/", "_")
60-
envPrefix = strings.ToUpper(strings.ReplaceAll(r.Replace(strcase.ToSnake(envPrefix))+"_", "__", "_"))
61-
62-
for name, val := range env.List() {
63-
if !strings.HasPrefix(name, envPrefix) || val == "" {
64-
continue
65-
}
66-
67-
envs := strings.SplitN(val, "=", 2)
68-
if len(envs) != 2 || envs[0] == "" {
69-
continue
70-
}
71-
72-
v.Set(strings.TrimSpace(envs[0]), strings.TrimSpace(envs[1]))
73-
}
74-
}
75-
7648
func Decode[Cfg any](c Config, name string) map[string]Cfg {
7749
var cfgMap = make(map[string]Cfg)
7850
xerror.PanicF(c.Decode(name, &cfgMap), "config decode failed, name=%s", name)

config/vars.go

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,23 +4,28 @@ import (
44
"github.com/pubgo/dix"
55
"github.com/pubgo/lava/internal/pkg/typex"
66
"github.com/pubgo/lava/vars"
7+
"sort"
78
)
89

910
func init() {
1011
vars.Register("config_data", func() interface{} {
11-
var conf = new(struct {
12-
C Config `inject:""`
13-
})
14-
dix.Inject(&conf)
12+
var conf = dix.Inject(new(struct{ C Config }))
1513
return conf.C.All()
1614
})
1715

16+
vars.Register("config_keys", func() interface{} {
17+
var conf = dix.Inject(new(struct{ C Config }))
18+
var keys = conf.C.AllKeys()
19+
sort.Strings(keys)
20+
return keys
21+
})
22+
1823
vars.Register("config", func() interface{} {
1924
return typex.M{
20-
"cfgType": CfgType,
21-
"cfgName": CfgName,
22-
"home": CfgDir,
23-
"cfgPath": CfgPath,
25+
"cfg_type": CfgType,
26+
"cfg_name": CfgName,
27+
"home": CfgDir,
28+
"cfg_path": CfgPath,
2429
}
2530
})
2631
}

configs/config/1.yaml

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
orm:
2+
- name: default1
3+
driver: "sqlite3"
4+
driver_config:
5+
dsn: "file::memory:?cache=shared"
6+
- name: test1
7+
driver: "sqlite3"
8+
driver_config:
9+
dsn: "file::memory:?cache=shared"
10+
redis:
11+
codis1:
12+
addr: "127.0.0.1:6379"
13+
password: "foobared"
14+
db: 0
15+
redisSale1:
16+
addr: "127.0.0.1:6379"
17+
password: "foobared"
18+
db: 0
19+
redisApiBusinessTwo1:
20+
addr: "127.0.0.1:6379"
21+
password: "foobared"
22+
db: 0
23+
redlock_0:
24+
addr: "127.0.0.1:6379"
25+
password: "foobared"
26+
db: 123

0 commit comments

Comments
 (0)