fix: 直接写入配置文件解决 viper 路径问题
This commit is contained in:
+37
-16
@@ -102,26 +102,47 @@ func Save(cfg *Config) error {
|
|||||||
return fmt.Errorf("创建数据目录失败: %w", err)
|
return fmt.Errorf("创建数据目录失败: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
viper.Set("server", cfg.Server)
|
// 直接写入配置文件,避免 viper 的路径问题
|
||||||
viper.Set("database", cfg.Database)
|
|
||||||
viper.Set("redis", cfg.Redis)
|
|
||||||
viper.Set("jwt", cfg.JWT)
|
|
||||||
viper.Set("captcha", cfg.Captcha)
|
|
||||||
|
|
||||||
// 使用 SafeWriteConfig,如果文件不存在会自动创建
|
|
||||||
configPath := "./data/config.yaml"
|
configPath := "./data/config.yaml"
|
||||||
viper.SetConfigFile(configPath)
|
|
||||||
|
|
||||||
// 检查文件是否存在,不存在则创建
|
// 构建 YAML 内容
|
||||||
if _, err := os.Stat(configPath); os.IsNotExist(err) {
|
content := fmt.Sprintf(`server:
|
||||||
if err := viper.SafeWriteConfig(); err != nil {
|
host: %s
|
||||||
return fmt.Errorf("创建配置文件失败: %w", err)
|
port: %d
|
||||||
}
|
mode: %s
|
||||||
return nil
|
database:
|
||||||
|
type: %s
|
||||||
|
host: %s
|
||||||
|
port: %d
|
||||||
|
user: %s
|
||||||
|
password: %s
|
||||||
|
database: %s
|
||||||
|
sqlite:
|
||||||
|
path: %s
|
||||||
|
redis:
|
||||||
|
enabled: %v
|
||||||
|
host: %s
|
||||||
|
port: %d
|
||||||
|
password: %s
|
||||||
|
db: %d
|
||||||
|
jwt:
|
||||||
|
secret: %s
|
||||||
|
expire_time: %d
|
||||||
|
captcha:
|
||||||
|
model_path: %s
|
||||||
|
`,
|
||||||
|
cfg.Server.Host, cfg.Server.Port, cfg.Server.Mode,
|
||||||
|
cfg.Database.Type, cfg.Database.Host, cfg.Database.Port, cfg.Database.User, cfg.Database.Password, cfg.Database.Database, cfg.Database.SQLite.Path,
|
||||||
|
cfg.Redis.Enabled, cfg.Redis.Host, cfg.Redis.Port, cfg.Redis.Password, cfg.Redis.DB,
|
||||||
|
cfg.JWT.Secret, cfg.JWT.ExpireTime,
|
||||||
|
cfg.Captcha.ModelPath,
|
||||||
|
)
|
||||||
|
|
||||||
|
if err := os.WriteFile(configPath, []byte(content), 0644); err != nil {
|
||||||
|
return fmt.Errorf("写入配置文件失败: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 文件已存在,直接写入
|
return nil
|
||||||
return viper.WriteConfig()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func IsInstalled() bool {
|
func IsInstalled() bool {
|
||||||
|
|||||||
Reference in New Issue
Block a user