From cef8b55fba80164f8022dd76215ca8d6968471f9 Mon Sep 17 00:00:00 2001 From: yanweidong Date: Thu, 18 Sep 2025 13:34:35 +0800 Subject: [PATCH] =?UTF-8?q?feat(conf/new.go):=20=E6=B7=BB=E5=8A=A0?= =?UTF-8?q?=E9=85=8D=E7=BD=AE=E6=96=87=E4=BB=B6=E4=B8=8D=E5=AD=98=E5=9C=A8?= =?UTF-8?q?=E6=97=B6=E7=9A=84=E5=A4=84=E7=90=86=E9=80=BB=E8=BE=91=E5=8F=8A?= =?UTF-8?q?=E7=8E=AF=E5=A2=83=E5=8F=98=E9=87=8F=E6=9B=BF=E6=8D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 在`New`函数中增加了对配置文件不存在时的处理逻辑,如果指定的服务配置文件不存在,则尝试读取基于工作空间的配置文件。此外,在加载YAML配置之前,新增了对环境变量的替换步骤,确保配置中的环境变量能够被正确解析。 这些改动提高了配置加载过程的灵活性与适应性,使得应用能够在缺少特定服务配置的情况下也能正常启动,并且支持通过环境变量动态调整配置内容。 --- conf/new.go | 11 ++++++++++- utils/file.go | 29 +++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/conf/new.go b/conf/new.go index c3069d5..c300074 100644 --- a/conf/new.go +++ b/conf/new.go @@ -30,6 +30,12 @@ func New(srvKey string, cfg any) { cfp := fmt.Sprintf("%s_%s.yaml", strings.ToLower(srvKey), env.Runtime.Mode) cfp = filepath.Join(env.Runtime.Prefix, "etc", cfp) + // 配置文件不存在则读取Workspace配置文件 + if !utils.PathExists(cfp) { + cfp = fmt.Sprintf("workspace_%s_%s.yaml", strings.ToLower(env.Runtime.Workspace), env.Runtime.Mode) + cfp = filepath.Join(env.Runtime.Prefix, "etc", cfp) + } + print.Info("[BSM - %s] Config File: %s", srvKey, cfp) print.Info("[BSM - %s] Check Configure ...", vars.ServiceKey) @@ -39,8 +45,11 @@ func New(srvKey string, cfg any) { log.Fatalf("ERROR: %v", err) } + // 替换环境变量 + yamlString := os.ExpandEnv(string(yamlFile)) + // 检查配置文件中是否存在Service和Port字段 - if !strings.Contains(string(yamlFile), "Service:") { + if !strings.Contains(yamlString, "Service:") { log.Fatalln("ERROR: Service Not Nil", cfp) } diff --git a/utils/file.go b/utils/file.go index bcc47a8..dd9e448 100644 --- a/utils/file.go +++ b/utils/file.go @@ -8,6 +8,14 @@ import ( "path/filepath" ) + +const ( + B = 1 + KB = 1024 * B + MB = 1024 * KB + GB = 1024 * MB +) + // 将字符串写入文件 func StringToFile(path, content string) error { startF, err := os.Create(path) @@ -48,6 +56,27 @@ func CopyFile(src, dst string) (int64, error) { return nBytes, err } + +func FileSize(fp string) string { + fileInfo, err := os.Stat(fp) + if err != nil { + return "0 B" + } + bytes := fileInfo.Size() + + switch { + case bytes >= GB: + return fmt.Sprintf("%.2f GB", float64(bytes)/float64(GB)) + case bytes >= MB: + return fmt.Sprintf("%.2f MB", float64(bytes)/float64(MB)) + case bytes >= KB: + return fmt.Sprintf("%.2f KB", float64(bytes)/float64(KB)) + default: + return fmt.Sprintf("%d B", bytes) + } +} + + // 递归遍历文件夹 // rootDir: 文件夹根目录 // s: 存储文件名的切片