config.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package config
  2. import (
  3. "fmt"
  4. "git.sxidc.com/go-framework/baize/framework/core/application"
  5. "git.sxidc.com/go-tools/utils/strutils"
  6. "git.sxidc.com/service-supports/fslog"
  7. "git.sxidc.com/service-supports/scm-sdk"
  8. "gopkg.in/yaml.v3"
  9. "os"
  10. )
  11. type Config struct {
  12. ApplicationConfig application.Config
  13. ServicesConfig ServicesConfig `yaml:"services"`
  14. }
  15. type ServicesConfig struct {
  16. TimeoutSec int64 `yaml:"timeout_sec"`
  17. ExampleBaseUrl string `yaml:"example_base_url"`
  18. }
  19. var conf Config
  20. func init() {
  21. useSCMEnv := os.Getenv("USE_SCM")
  22. if useSCMEnv == "true" {
  23. initConfigFromSCM()
  24. } else {
  25. initConfigFromConfigFile()
  26. }
  27. }
  28. func GetConfig() Config {
  29. return conf
  30. }
  31. func initConfigFromSCM() {
  32. scmBaseUrl := loadEnvOrPanic("SCM_BASE_URL")
  33. scmNamespace := loadEnvOrPanic("SCM_NAMESPACE")
  34. scmName := loadEnvOrPanic("SCM_NAME")
  35. info, err := scm_sdk.GetCurrentConfiguration(scmBaseUrl, scmNamespace, scmName)
  36. if err != nil {
  37. fslog.Error(err)
  38. panic(err)
  39. }
  40. applicationConfig, err := application.LoadFromYaml(info.Content)
  41. if err != nil {
  42. panic(err)
  43. }
  44. conf.ApplicationConfig = applicationConfig
  45. err = yaml.Unmarshal([]byte(info.Content), &conf)
  46. if err != nil {
  47. panic(err)
  48. }
  49. fslog.Info("Load config from scm finish")
  50. }
  51. func initConfigFromConfigFile() {
  52. configFilePath := os.Getenv("CONFIG_FILE_PATH")
  53. applicationConfig, err := application.LoadFromYamlFile(configFilePath)
  54. if err != nil {
  55. panic(err)
  56. }
  57. conf.ApplicationConfig = applicationConfig
  58. yamlBytes, err := os.ReadFile(configFilePath)
  59. if err != nil {
  60. panic(err)
  61. }
  62. err = yaml.Unmarshal(yamlBytes, &conf)
  63. if err != nil {
  64. panic(err)
  65. }
  66. fmt.Println("Load config file finish")
  67. }
  68. func loadEnvOrPanic(envName string) string {
  69. envValue := os.Getenv(envName)
  70. if strutils.IsStringEmpty(envValue) {
  71. panic("请配置" + envName)
  72. }
  73. return envValue
  74. }