From b61d8aae8fdb884329b652df0fda62e282d6fa19 Mon Sep 17 00:00:00 2001 From: skyle1995 Date: Fri, 31 Oct 2025 09:38:36 +0800 Subject: [PATCH] Optimize the output of sensitive log information --- cmd/root.go | 14 +++++++-- cmd/server.go | 2 ++ config/config.go | 57 ++++++++++++++++++++++++++--------- config/validator.go | 12 +++++++- database/database.go | 15 ++++++++-- utils/filepath.go | 71 ++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 151 insertions(+), 20 deletions(-) create mode 100755 utils/filepath.go diff --git a/cmd/root.go b/cmd/root.go index 0472b96..f9c182b 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -81,8 +81,16 @@ func setupLogrusForNonHTTP() { // 使用命令行指定的配置文件 config.Init(cfgFile) } else { - // 使用默认配置文件路径 - config.Init("./config.json") + // 使用默认配置文件路径,基于可执行文件所在目录 + execPath, err := os.Executable() + if err != nil { + // 如果获取可执行文件路径失败,使用当前工作目录 + config.Init("./config.json") + } else { + execDir := filepath.Dir(execPath) + configPath := filepath.Join(execDir, "config.json") + config.Init(configPath) + } } // 根据配置文件进一步配置logrus @@ -92,7 +100,7 @@ func setupLogrusForNonHTTP() { logger.InitLogger() // 记录配置加载完成 - logrus.WithField("config_file", viper.ConfigFileUsed()).Info("配置文件加载完成") + logrus.Info("配置文件加载完成") } // initConfig 读取配置文件和环境变量 diff --git a/cmd/server.go b/cmd/server.go index f723925..90ec85e 100644 --- a/cmd/server.go +++ b/cmd/server.go @@ -174,6 +174,8 @@ func startServer(server *http.Server) { // 等待中断信号 <-sigChan + // 清除终端上的 ^C 字符并移动光标到行首 + fmt.Print("\r\033[K") logger.Info("收到关闭信号,正在优雅关闭服务器...") // 创建一个带超时的上下文 diff --git a/config/config.go b/config/config.go index 6929949..6cbbe9f 100644 --- a/config/config.go +++ b/config/config.go @@ -6,9 +6,11 @@ import ( "errors" "io/fs" "os" + "path/filepath" log "github.com/sirupsen/logrus" "github.com/spf13/viper" + "networkDev/utils" ) // ============================================================================ @@ -115,9 +117,9 @@ func GetDefaultAppConfig() *AppConfig { MySQL: MySQLConfig{ Host: "localhost", Port: 3306, - Username: "root", - Password: "password", - Database: "networkdev", + Username: "", + Password: "", + Database: "", Charset: "utf8mb4", MaxIdleConns: 10, MaxOpenConns: 100, @@ -172,7 +174,17 @@ func GetSecureDefaultAppConfig() (*AppConfig, error) { // Init 初始化配置文件 func Init(cfgFilePath string) { - viper.SetConfigFile(cfgFilePath) + // 确保配置文件路径为绝对路径 + absoluteConfigPath, err := utils.EnsureAbsolutePath(cfgFilePath) + if err != nil { + log.WithFields( + log.Fields{ + "err": err, + "path": cfgFilePath, + }, + ).Fatal("转换配置文件路径为绝对路径失败") + } + viper.SetConfigFile(absoluteConfigPath) viper.SetConfigType("json") viper.AddConfigPath(".") @@ -203,8 +215,8 @@ func Init(cfgFilePath string) { return } - // 写入配置文件 - err = os.WriteFile(cfgFilePath, configBytes, 0o644) + // 写入配置文件,使用绝对路径 + err = os.WriteFile(absoluteConfigPath, configBytes, 0o644) if err != nil { log.WithFields( log.Fields{ @@ -212,9 +224,11 @@ func Init(cfgFilePath string) { }, ).Error("写入默认配置文件失败") } else { + // 只显示配置文件名,不显示完整路径 + fileName := filepath.Base(cfgFilePath) log.WithFields( log.Fields{ - "file": cfgFilePath, + "file": fileName, }, ).Info("写入默认配置文件成功(已生成安全密钥)") } @@ -238,11 +252,20 @@ func Init(cfgFilePath string) { ).Fatal("配置文件解析错误") } } - log.WithFields( - log.Fields{ - "file": viper.ConfigFileUsed(), - }, - ).Info("使用配置文件") + + // 只显示配置文件名,不显示完整路径 + configFile := viper.ConfigFileUsed() + if configFile != "" { + // 提取文件名 + fileName := filepath.Base(configFile) + log.WithFields( + log.Fields{ + "file": fileName, + }, + ).Info("使用配置文件") + } else { + log.Info("使用默认配置") + } // 验证配置 if _, err := ValidateConfig(); err != nil { @@ -250,12 +273,18 @@ func Init(cfgFilePath string) { log.Fields{ "err": err, }, - ).Fatal("配置验证失败") + ).Fatal("配置内容验证失败") } } // CreateDefaultConfig 创建默认配置文件 func CreateDefaultConfig(filePath string) error { + // 确保文件路径为绝对路径 + absoluteFilePath, err := utils.EnsureAbsolutePath(filePath) + if err != nil { + return err + } + // 生成带有安全密钥的默认配置 defaultConfig, err := GetSecureDefaultAppConfig() if err != nil { @@ -273,5 +302,5 @@ func CreateDefaultConfig(filePath string) error { return err } - return os.WriteFile(filePath, configBytes, 0o644) + return os.WriteFile(absoluteFilePath, configBytes, 0o644) } diff --git a/config/validator.go b/config/validator.go index 67db127..18e6fd6 100644 --- a/config/validator.go +++ b/config/validator.go @@ -11,6 +11,7 @@ import ( log "github.com/sirupsen/logrus" "github.com/spf13/viper" + "networkDev/utils" ) // ============================================================================ @@ -31,7 +32,7 @@ func ValidateConfig() (*AppConfig, error) { return nil, fmt.Errorf("配置验证失败: %w", err) } - log.Info("配置验证通过") + log.Info("配置内容验证通过") return &config, nil } @@ -134,6 +135,15 @@ func validateSQLiteConfig(config *SQLiteConfig) error { return errors.New("SQLite数据库路径不能为空") } + // 确保数据库路径为绝对路径 + absolutePath, err := utils.EnsureAbsolutePath(config.Path) + if err != nil { + return fmt.Errorf("转换SQLite数据库路径为绝对路径失败: %w", err) + } + + // 更新配置中的路径为绝对路径 + config.Path = absolutePath + // 检查目录是否存在,不存在则创建 dir := filepath.Dir(config.Path) if _, err := os.Stat(dir); os.IsNotExist(err) { diff --git a/database/database.go b/database/database.go index d3f6f98..5ce0078 100644 --- a/database/database.go +++ b/database/database.go @@ -3,6 +3,7 @@ package database import ( "fmt" "networkDev/utils" + "path/filepath" "sync" "github.com/glebarez/sqlite" @@ -91,7 +92,15 @@ func initSQLite() error { if path == "" { path = "./database.db" } - dsn := fmt.Sprintf("file:%s?cache=shared&_busy_timeout=5000&_fk=1", path) + + // 确保数据库路径为绝对路径 + absolutePath, err := utils.EnsureAbsolutePath(path) + if err != nil { + logrus.WithError(err).Error("转换SQLite数据库路径为绝对路径失败") + return err + } + + dsn := fmt.Sprintf("file:%s?cache=shared&_busy_timeout=5000&_fk=1", absolutePath) db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{}) if err != nil { logrus.WithError(err).Error("SQLite 初始化失败") @@ -106,7 +115,9 @@ func initSQLite() error { } dbInstance = db - logrus.WithField("path", path).Info("SQLite 连接已建立") + // 记录连接成功信息(只显示文件名,不泄露完整路径) + fileName := filepath.Base(absolutePath) + logrus.WithField("file", fileName).Info("SQLite 连接已建立") return nil } diff --git a/utils/filepath.go b/utils/filepath.go new file mode 100755 index 0000000..18a8b55 --- /dev/null +++ b/utils/filepath.go @@ -0,0 +1,71 @@ +package utils + +import ( + "errors" + "os" + "path/filepath" +) + +// EnsureAbsolutePath 确保路径为绝对路径 +// 如果传入的路径已经是绝对路径,直接返回 +// 如果是相对路径,则基于当前工作目录转换为绝对路径 +func EnsureAbsolutePath(path string) (string, error) { + if filepath.IsAbs(path) { + return path, nil + } + + // 获取当前工作目录 + currentDir, err := os.Getwd() + if err != nil { + return "", errors.New("获取当前工作目录失败") + } + + // 将相对路径转换为绝对路径 + return filepath.Join(currentDir, path), nil +} + +// EnsureAbsolutePathWithBase 基于指定基础目录确保路径为绝对路径 +// 如果传入的路径已经是绝对路径,直接返回 +// 如果是相对路径,则基于指定的基础目录转换为绝对路径 +func EnsureAbsolutePathWithBase(path, baseDir string) (string, error) { + if filepath.IsAbs(path) { + return path, nil + } + + // 确保基础目录是绝对路径 + absBaseDir, err := EnsureAbsolutePath(baseDir) + if err != nil { + return "", errors.New("基础目录路径处理失败") + } + + // 将相对路径转换为绝对路径 + return filepath.Join(absBaseDir, path), nil +} + +// GetExecutableDir 获取可执行文件所在目录的绝对路径 +func GetExecutableDir() (string, error) { + execPath, err := os.Executable() + if err != nil { + return "", errors.New("获取可执行文件路径失败") + } + return filepath.Dir(execPath), nil +} + +// EnsureAbsolutePathFromExecutable 基于可执行文件目录确保路径为绝对路径 +// 如果传入的路径已经是绝对路径,直接返回 +// 如果是相对路径,则基于可执行文件所在目录转换为绝对路径 +func EnsureAbsolutePathFromExecutable(path string) (string, error) { + if filepath.IsAbs(path) { + return path, nil + } + + // 获取可执行文件目录 + execDir, err := GetExecutableDir() + if err != nil { + // 如果获取可执行文件目录失败,回退到当前工作目录 + return EnsureAbsolutePath(path) + } + + // 将相对路径转换为绝对路径 + return filepath.Join(execDir, path), nil +} \ No newline at end of file