diff --git a/internal/config/config.go b/internal/config/config.go index debdc56..d8723e8 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -102,26 +102,47 @@ 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) - } - return nil + // 构建 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 viper.WriteConfig() + return nil } func IsInstalled() bool {