fix: 直接写入配置文件解决 viper 路径问题
This commit is contained in:
+37
-16
@@ -102,28 +102,49 @@ func Save(cfg *Config) error {
|
||||
return fmt.Errorf("创建数据目录失败: %w", err)
|
||||
}
|
||||
|
||||
viper.Set("server", cfg.Server)
|
||||
viper.Set("database", cfg.Database)
|
||||
viper.Set("redis", cfg.Redis)
|
||||
viper.Set("jwt", cfg.JWT)
|
||||
viper.Set("captcha", cfg.Captcha)
|
||||
|
||||
// 使用 SafeWriteConfig,如果文件不存在会自动创建
|
||||
// 直接写入配置文件,避免 viper 的路径问题
|
||||
configPath := "./data/config.yaml"
|
||||
viper.SetConfigFile(configPath)
|
||||
|
||||
// 检查文件是否存在,不存在则创建
|
||||
if _, err := os.Stat(configPath); os.IsNotExist(err) {
|
||||
if err := viper.SafeWriteConfig(); err != nil {
|
||||
return fmt.Errorf("创建配置文件失败: %w", err)
|
||||
// 构建 YAML 内容
|
||||
content := fmt.Sprintf(`server:
|
||||
host: %s
|
||||
port: %d
|
||||
mode: %s
|
||||
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 {
|
||||
_, err := os.Stat("./data/config.yaml")
|
||||
return err == nil
|
||||
|
||||
Reference in New Issue
Block a user