package config import ( "os" "path/filepath" "runtime" "sync" "time" "github.com/go-playground/validator" "github.com/rs/zerolog" "github.com/rs/zerolog/log" "github.com/spf13/viper" ) type casdoorConfig struct { Endpoint string `validate:"required" mapstructure:"endpoint"` ClientID string `validate:"required" mapstructure:"client_id"` ClientSecret string `validate:"required" mapstructure:"client_secret"` Certificate string `validate:"required" mapstructure:"certificate"` OrganizationName string `validate:"required" mapstructure:"organization_name"` AppName string `validate:"required" mapstructure:"app_name"` } type Config struct { IsLocal bool Debug bool `mapstructure:"debug"` HTTPPort int `mapstructure:"http_port" validate:"required"` Host string `mapstructure:"host" validate:"required"` Casdoor casdoorConfig `mapstructure:"casdoor"` Databases struct { Storage string `mapstructure:"storage" validate:"required"` PostgreSQL string `mapstructure:"postgresql" validate:"required"` Qdrant string `mapstructure:"qdrant" validate:"required"` } `mapstructure:"databases"` Sentry struct { Environment string `mapstructure:"environment"` DSN string `mapstructure:"dsn"` } `mapstructure:"sentry"` } var ( c *Config once sync.Once ) func Get() *Config { once.Do(setup) return c } func setup() { _, b, _, _ := runtime.Caller(0) projectRoot := filepath.Join(filepath.Dir(b), "../..") viper.SetConfigName("config") viper.AddConfigPath(projectRoot + "/configs") viper.AddConfigPath("/etc/octopus/") viper.AddConfigPath(projectRoot) err := viper.ReadInConfig() if _, ok := err.(viper.ConfigFileNotFoundError); ok { log.Info().Msg("config files not found, ignoring") } else if err != nil { log.Warn().Err(err).Msg("read config failed") } // unmarshal it if err := viper.Unmarshal(&c); err != nil { log.Fatal().Err(err).Msg("unmarshal config failed") } if c.Debug { log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339}) } // and validate it v := validator.New() if err := v.Struct(c); err != nil { log.Fatal().Err(err).Msg("validate config failed") } log.Info().Msg("load configs success") }