config.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. "os"
  9. )
  10. type Config struct {
  11. ApplicationConfig application.Config
  12. }
  13. var conf Config
  14. func init() {
  15. useSCMEnv := os.Getenv("USE_SCM")
  16. if useSCMEnv == "true" {
  17. initConfigFromSCM()
  18. } else {
  19. initConfigFromConfigFile()
  20. }
  21. }
  22. func GetConfig() Config {
  23. return conf
  24. }
  25. func initConfigFromSCM() {
  26. scmBaseUrl := loadEnvOrPanic("SCM_BASE_URL")
  27. scmNamespace := loadEnvOrPanic("SCM_NAMESPACE")
  28. scmName := loadEnvOrPanic("SCM_NAME")
  29. info, err := scm_sdk.GetCurrentConfiguration(scmBaseUrl, scmNamespace, scmName)
  30. if err != nil {
  31. fslog.Error(err)
  32. panic(err)
  33. }
  34. applicationConfig, err := application.LoadFromYaml(info.Content)
  35. if err != nil {
  36. panic(err)
  37. }
  38. conf.ApplicationConfig = applicationConfig
  39. fslog.Info("Load config from scm finish")
  40. }
  41. func initConfigFromConfigFile() {
  42. configFilePath := os.Getenv("CONFIG_FILE_PATH")
  43. applicationConfig, err := application.LoadFromYamlFile(configFilePath)
  44. if err != nil {
  45. panic(err)
  46. }
  47. conf.ApplicationConfig = applicationConfig
  48. fmt.Println("Load config file finish")
  49. }
  50. func loadEnvOrPanic(envName string) string {
  51. envValue := os.Getenv(envName)
  52. if strutils.IsStringEmpty(envValue) {
  53. panic("请配置" + envName)
  54. }
  55. return envValue
  56. }