package application import ( "encoding/json" "git.sxidc.com/go-framework/baize/infrastructure" "git.sxidc.com/go-tools/utils/fileutils" "git.sxidc.com/service-supports/fserr" "gopkg.in/yaml.v3" "os" ) type Config struct { ApiConfig `json:"api" yaml:"api"` InfrastructureConfig `json:"infrastructure" yaml:"infrastructure"` } type ApiConfig struct { UrlPrefix string `json:"url_prefix" yaml:"url_prefix"` Port string `json:"port" yaml:"port"` } type InfrastructureConfig struct { Database infrastructure.DatabaseConfig `json:"database" yaml:"database"` } func LoadFromJsonFile(jsonFilePath string) (Config, error) { if !fileutils.PathExists(jsonFilePath) { return Config{}, fserr.New("配置文件不存在") } jsonBytes, err := os.ReadFile(jsonFilePath) if err != nil { return Config{}, err } return loadFromJson(jsonBytes) } func LoadFromYamlFile(yamlFilePath string) (Config, error) { if !fileutils.PathExists(yamlFilePath) { return Config{}, fserr.New("配置文件不存在") } yamlBytes, err := os.ReadFile(yamlFilePath) if err != nil { return Config{}, err } return loadFromYaml(yamlBytes) } func LoadFromJson(jsonStr string) (Config, error) { return loadFromJson([]byte(jsonStr)) } func LoadFromYaml(yamlStr string) (Config, error) { return loadFromYaml([]byte(yamlStr)) } func loadFromJson(jsonBytes []byte) (Config, error) { conf := new(Config) err := json.Unmarshal(jsonBytes, conf) if err != nil { return Config{}, err } return *conf, nil } func loadFromYaml(yamlBytes []byte) (Config, error) { conf := new(Config) err := yaml.Unmarshal(yamlBytes, conf) if err != nil { return Config{}, err } return *conf, nil }