fermentord/internal/configuration/config.go
Søren Rasmussen 4ef93fb6cf
Some checks reported errors
continuous-integration/drone/push Build encountered an error
Allow configuration by environment
2024-06-15 22:49:09 +02:00

64 lines
1 KiB
Go

package configuration
import (
"bytes"
_ "embed"
"log"
"strings"
"sync"
"github.com/getsentry/sentry-go"
"github.com/spf13/viper"
)
var (
globalConfig Configuration
globalLock *sync.Mutex
//go:embed fermentord.toml
globalData []byte
)
func init() {
globalLock = &sync.Mutex{}
}
func Global() Configuration {
globalLock.Lock()
defer globalLock.Unlock()
return globalConfig
}
func Initialize() {
setDefaults()
viper.SetConfigName("fermentord")
viper.SetEnvPrefix("fermentord")
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "__"))
}
func LoadConfiguration() Configuration {
globalLock.Lock()
defer globalLock.Unlock()
buf := bytes.NewBuffer(globalData)
if err := viper.ReadConfig(buf); err != nil {
panic(err)
}
if err := viper.MergeInConfig(); err != nil {
log.Printf("Error loading configuration: %v", err)
}
viper.AutomaticEnv()
config := Configuration{}
if err := viper.Unmarshal(&config); err != nil {
sentry.CaptureException(err)
log.Fatal(err)
}
globalConfig = config
return globalConfig
}