package config import ( "log/slog" "os" "github.com/spf13/viper" ) // Config . type Config struct { DataBase *DataBase `json:"database" yaml:"database"` Timezone string `json:"timezone" yaml:"timezone"` Logging *Logging `json:"logging" yaml:"logging"` } // DB . type DataBase struct { DSN string `json:"dsn" yaml:"dsn"` } // Logging . type Logging struct { Level string `json:"level" yaml:"level"` Output string `json:"output" yaml:"output"` Source bool `json:"source,omitempty" yaml:"source,omitempty"` } // New . func New() (*Config, error) { viper.SetConfigName("config") // name of config file (without extension) viper.SetConfigType("yml") // REQUIRED if the config file does not have the extension in the name viper.AddConfigPath("./") // optionally look for config in the working directory viper.AddConfigPath("/etc/tracker") // optionally look for config in the working directory viper.AutomaticEnv() viper.SetDefault("Timezone", "America/New_York") viper.SetDefault("Logging.Level", "DEBUG") viper.SetDefault("Logging.Output", "TEXT") viper.SetDefault("Logging.Source", "false") err := viper.ReadInConfig() // Find and read the config file if err != nil { slog.Error("cannot open config file", "error", err.Error()) os.Exit(1) } // viper.WatchConfig() // viper.OnConfigChange(func(e fsnotify.Event) { // log.Println("Config file changed:", e.Name) // }) var config Config if err := viper.Unmarshal(&config); err != nil { slog.Error("cannot unmarshal config file", "error", err.Error()) os.Exit(1) } return &config, err }