bingobot/internal/config/config.go
Ava Affine 6afd0122c9 Fix config unit tests
Recent changes to config and logging modules have left the tests needing
to initialize both config and logging packages. This commit updates the
config module to automatically initialize into at least useful defaults
at module load time. This commit also fixes the config unit tests by
using the more up to date interface that the package provides.

Signed-off-by: Ava Affine <ava@sunnypup.io>
2024-11-14 10:27:45 -08:00

69 lines
1.4 KiB
Go

package config
import (
"fmt"
"github.com/spf13/viper"
)
type AppConfig struct {
LogFile string `yaml:"log_file"`
LogDir string `yaml:"log_dir"`
LogMaxSizeMB int `yaml:"log_max_size_mb"`
LogMaxBackups int `yaml:"log_max_backups"`
LogMaxAgeDays int `yaml:"log_max_age_days"`
LogCompression bool `yaml:"log_compression"`
LogAddSource bool `yaml:"log_add_source"`
}
var config *AppConfig
func init() {
setDefaults()
viper.Unmarshal(&config)
}
func Get() *AppConfig {
return config
}
func GetDefaultConfig() *AppConfig {
var config *AppConfig
setDefaults()
viper.Unmarshal(&config)
return config
}
func Init() error {
setDefaults()
// automatically populate config with any matching environment vars
viper.SetEnvPrefix("BB")
viper.AutomaticEnv()
viper.SetConfigName("config")
viper.SetConfigType("yaml")
viper.AddConfigPath(".")
err := viper.ReadInConfig()
if err != nil {
return fmt.Errorf("error reading configs: %s", err)
}
err = viper.Unmarshal(&config)
if err != nil {
return fmt.Errorf("error unmarshaling configs: %s", err)
}
return nil
}
func setDefaults() {
viper.SetDefault("LogFile", "bingobot.log")
viper.SetDefault("LogDir", "log")
viper.SetDefault("LogMaxSizeMB", 500)
viper.SetDefault("LogMaxBackups", 3)
viper.SetDefault("LogMaxAgeDays", 365)
viper.SetDefault("LogCompression", false)
viper.SetDefault("LogAddSource", true)
}