123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- package config
- import (
- "fmt"
- "git.sxidc.com/go-framework/baize/framework/core/application"
- "git.sxidc.com/go-tools/utils/strutils"
- "git.sxidc.com/service-supports/fslog"
- "git.sxidc.com/service-supports/scm-sdk"
- "gopkg.in/yaml.v3"
- "os"
- )
- type Config struct {
- ApplicationConfig application.Config
- ServicesConfig ServicesConfig `yaml:"services"`
- }
- type ServicesConfig struct {
- TimeoutSec int64 `yaml:"timeout_sec"`
- ExampleBaseUrl string `yaml:"example_base_url"`
- }
- var conf Config
- func init() {
- useSCMEnv := os.Getenv("USE_SCM")
- if useSCMEnv == "true" {
- initConfigFromSCM()
- } else {
- initConfigFromConfigFile()
- }
- }
- func GetConfig() Config {
- return conf
- }
- func initConfigFromSCM() {
- scmBaseUrl := loadEnvOrPanic("SCM_BASE_URL")
- scmNamespace := loadEnvOrPanic("SCM_NAMESPACE")
- scmName := loadEnvOrPanic("SCM_NAME")
- info, err := scm_sdk.GetCurrentConfiguration(scmBaseUrl, scmNamespace, scmName)
- if err != nil {
- fslog.Error(err)
- panic(err)
- }
- applicationConfig, err := application.LoadFromYaml(info.Content)
- if err != nil {
- panic(err)
- }
- conf.ApplicationConfig = applicationConfig
- err = yaml.Unmarshal([]byte(info.Content), &conf)
- if err != nil {
- panic(err)
- }
- fslog.Info("Load config from scm finish")
- }
- func initConfigFromConfigFile() {
- configFilePath := os.Getenv("CONFIG_FILE_PATH")
- applicationConfig, err := application.LoadFromYamlFile(configFilePath)
- if err != nil {
- panic(err)
- }
- conf.ApplicationConfig = applicationConfig
- yamlBytes, err := os.ReadFile(configFilePath)
- if err != nil {
- panic(err)
- }
- err = yaml.Unmarshal(yamlBytes, &conf)
- if err != nil {
- panic(err)
- }
- fmt.Println("Load config file finish")
- }
- func loadEnvOrPanic(envName string) string {
- envValue := os.Getenv(envName)
- if strutils.IsStringEmpty(envValue) {
- panic("请配置" + envName)
- }
- return envValue
- }
|