package config import ( "flag" "fmt" "os" "strings" "be.ems/lib/global" "be.ems/lib/log" "gopkg.in/yaml.v3" ) type DbConfig struct { Type string `yaml:"type"` User string `yaml:"user"` Password string `yaml:"password"` Host string `yaml:"host"` Port string `yaml:"port"` Name string `yaml:"name"` ConnParam string `yaml:"connParam,omitempty"` Backup string `yaml:"backup"` } // Yaml struct of config type YamlConfig struct { Logger struct { File string `yaml:"file"` Level string `yaml:"level"` Duration int `yaml:"duration"` Count int `yaml:"count"` } `yaml:"logger"` Gtp struct { Addr string `yaml:"addr"` } `yaml:"gtp"` Database DbConfig `yaml:"database"` } var YamlConf YamlConfig = NewYamlConfig() // set default value for yaml config func NewYamlConfig() YamlConfig { return YamlConfig{ Database: DbConfig{ Type: "mysql", ConnParam: "charset=utf8mb4&collation=utf8mb4_general_ci&loc=Local", }, } } func ReadConfig(configFile string) { yamlFile, err := os.ReadFile(configFile) if err != nil { fmt.Println("Read yaml config file error:", err) os.Exit(2) } // fmt.Println("yamlfile:", string(yamlFile)) err = yaml.Unmarshal(yamlFile, &YamlConf) if err != nil { fmt.Println("Unmarshal error:", err) os.Exit(3) } } func WriteYamlConfig(newConfigData YamlConfig, configFile string) { // 将配置转换回YAML数据 newYamlData, err := yaml.Marshal(&newConfigData) if err != nil { log.Errorf("Failed to marshal YAML: %v", err) } // 将新的YAML数据写入文件 err = os.WriteFile(configFile, newYamlData, 0644) if err != nil { log.Errorf("Failed to write YAML file: %v", err) } } func GetYamlConfig() *YamlConfig { return &YamlConf } func GetLogLevel() log.LogLevel { var logLevel log.LogLevel switch strings.ToLower(YamlConf.Logger.Level) { case "trace": logLevel = log.LOG_TRACE case "info": logLevel = log.LOG_INFO case "debug": logLevel = log.LOG_DEBUG case "warn": logLevel = log.LOG_WARN case "error": logLevel = log.LOG_ERROR case "fatal": logLevel = log.LOG_FATAL case "off": logLevel = log.LOG_OFF default: logLevel = log.LOG_DEBUG } return logLevel } const defaultConfigFile = "./etc/capconf.yaml" func init() { cfile := flag.String("c", defaultConfigFile, "config file") pv := flag.Bool("version", false, "print version") ph := flag.Bool("help", false, "print help") flag.Parse() if *pv { fmt.Printf("OMC captrace version: %s\n%s\n%s\n\n", global.Version, global.BuildTime, global.GoVer) os.Exit(0) } if *ph { flag.Usage() os.Exit(0) } ReadConfig(*cfile) }