config.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. OssConfig ossConfig `yaml:"oss"`
  14. }
  15. var conf Config
  16. func init() {
  17. useSCMEnv := os.Getenv("USE_SCM")
  18. if useSCMEnv == "true" {
  19. initConfigFromSCM()
  20. } else {
  21. initConfigFromConfigFile()
  22. }
  23. }
  24. func GetConfig() Config {
  25. return conf
  26. }
  27. type ossConfig struct {
  28. Endpoint string `yaml:"endpoint"`
  29. KeyID string `yaml:"key_id"`
  30. KeySecret string `yaml:"key_secret"`
  31. Prefix string `yaml:"prefix"`
  32. TmpPrefix string `yaml:"tmp_prefix"`
  33. }
  34. func initConfigFromSCM() {
  35. scmBaseUrl := loadEnvOrPanic("SCM_BASE_URL")
  36. scmNamespace := loadEnvOrPanic("SCM_NAMESPACE")
  37. scmName := loadEnvOrPanic("SCM_NAME")
  38. info, err := scm_sdk.GetCurrentConfiguration(scmBaseUrl, scmNamespace, scmName)
  39. if err != nil {
  40. fslog.Error(err)
  41. panic(err)
  42. }
  43. applicationConfig, err := application.LoadFromYaml(info.Content)
  44. if err != nil {
  45. panic(err)
  46. }
  47. conf.ApplicationConfig = applicationConfig
  48. err = yaml.Unmarshal([]byte(info.Content), &conf)
  49. if err != nil {
  50. panic(err)
  51. }
  52. fslog.Info("Load config from scm finish")
  53. }
  54. func initConfigFromConfigFile() {
  55. configFilePath := os.Getenv("CONFIG_FILE_PATH")
  56. applicationConfig, err := application.LoadFromYamlFile(configFilePath)
  57. if err != nil {
  58. panic(err)
  59. }
  60. conf.ApplicationConfig = applicationConfig
  61. yamlBytes, err := os.ReadFile(configFilePath)
  62. if err != nil {
  63. panic(err)
  64. }
  65. err = yaml.Unmarshal(yamlBytes, &conf)
  66. if err != nil {
  67. panic(err)
  68. }
  69. fmt.Println("Load config file finish")
  70. }
  71. func loadEnvOrPanic(envName string) string {
  72. envValue := os.Getenv(envName)
  73. if strutils.IsStringEmpty(envValue) {
  74. panic("请配置" + envName)
  75. }
  76. return envValue
  77. }