11package config
22
33import (
4+ "bytes"
45 "fmt"
56 "io"
67 "io/fs"
78 "path/filepath"
89 "reflect"
910 "strings"
1011 "sync"
12+ "text/template"
1113
1214 "github.com/mitchellh/mapstructure"
1315 "github.com/pubgo/funk"
@@ -16,7 +18,6 @@ import (
1618 "github.com/pubgo/xerror"
1719 "github.com/spf13/cast"
1820 "github.com/spf13/viper"
19- "github.com/valyala/fasttemplate"
2021
2122 "github.com/pubgo/lava/consts"
2223 "github.com/pubgo/lava/internal/pkg/env"
@@ -47,7 +48,7 @@ func newCfg() *configImpl {
4748 // 配置文件名字和类型
4849 v .SetConfigType (CfgType )
4950 v .SetConfigName (CfgName )
50- v .SetEnvKeyReplacer (strings .NewReplacer ("." , "_" , "-" , "_" ))
51+ v .SetEnvKeyReplacer (strings .NewReplacer ("." , "_" , "-" , "_" , "/" , "_" ))
5152 v .SetEnvPrefix (strings .ToUpper (EnvPrefix ))
5253 v .AutomaticEnv ()
5354
@@ -258,17 +259,22 @@ func (t *configImpl) LoadPath(path string) {
258259
259260 fmt .Printf ("load config %s\n " , path )
260261
261- tmp , err := fasttemplate .NewTemplate (xerror .PanicStr (iox .ReadText (path )), "{{" , "}}" )
262- xerror .Panic (err , "unexpected error when parsing template" )
263-
264- // 重新加载配置
265- xerror .Panic (t .v .MergeConfig (strings .NewReader (tmp .ExecuteFuncString (func (w io.Writer , tag string ) (int , error ) {
266- tag = strings .TrimSpace (tag )
267- // 处理配置中的环境变量
268- if strings .HasPrefix (tag , "$" ) {
269- return w .Write ([]byte (env .Get (tag )))
270- }
271-
272- return w .Write ([]byte (t .v .GetString (tag )))
273- }))))
262+ tmpl := funk .Must1 (template .New ("" ).Funcs (template.FuncMap {
263+ "upper" : strings .ToUpper ,
264+ "env" : env .Get ,
265+ "trim" : strings .TrimSpace ,
266+ "v" : t .v .GetString ,
267+ "default" : func (a string , b string ) string {
268+ if strings .TrimSpace (b ) == "" {
269+ return a
270+ }
271+ return b
272+ },
273+ }).Parse (funk .Must1 (iox .ReadText (path ))))
274+
275+ var buf bytes.Buffer
276+ funk .Must (tmpl .Execute (& buf , map [string ]string {}))
277+
278+ // 合并配置
279+ funk .Must (t .v .MergeConfig (& buf ))
274280}
0 commit comments