package config import ( "fmt" "io/ioutil" "os" "path/filepath" "sync" "encoding/json" "gopkg.in/yaml.v2" ) // Config 系统配置结构体 type Config struct { Server ServerConfig `yaml:"server" json:"server"` Storage StorageConfig `yaml:"storage" json:"storage"` } // ServerConfig 服务器配置 type ServerConfig struct { Host string `yaml:"host" json:"host"` Port int `yaml:"port" json:"port"` } // StorageConfig 存储配置 type StorageConfig struct { Engine string `yaml:"engine" json:"engine"` DataPath string `yaml:"dataPath" json:"dataPath"` } var ( configInstance *Config once sync.Once ) // NewDefaultConfig 创建默认配置 func NewDefaultConfig() *Config { return &Config{ Server: ServerConfig{ Host: "0.0.0.0", Port: 27017, }, Storage: StorageConfig{ Engine: "memory", DataPath: "/var/lib/goaidb", }, } } // ParseConfig 解析配置文件 // 支持JSON和YAML格式 // 返回解析后的配置对象和错误信息 func ParseConfig(filePath string) (*Config, error) { // 检查文件是否存在 if _, err := os.Stat(filePath); os.IsNotExist(err) { return nil, fmt.Errorf("配置文件不存在: %s", filePath) } // 读取文件内容 data, err := ioutil.ReadFile(filePath) if err != nil { return nil, fmt.Errorf("读取配置文件失败: %v", err) } // 根据文件扩展名选择解析方式 var cfg Config switch filepath.Ext(filePath) { case ".json": if err := json.Unmarshal(data, &cfg); err != nil { return nil, fmt.Errorf("JSON解析失败: %v", err) } case ".yaml", ".yml": if err := yaml.Unmarshal(data, &cfg); err != nil { return nil, fmt.Errorf("YAML解析失败: %v", err) } default: return nil, fmt.Errorf("不支持的配置文件格式") } return &cfg, nil } // GetConfig 获取全局配置实例 func GetConfig() *Config { once.Do(func() { configInstance = NewDefaultConfig() }) return configInstance }