fermentord/internal/configuration/config.go

61 lines
958 B
Go
Raw Normal View History

2022-03-11 20:06:33 +00:00
package configuration
import (
2024-06-15 14:20:32 +00:00
"bytes"
_ "embed"
2022-03-11 20:06:33 +00:00
"log"
2022-08-02 05:26:41 +00:00
"sync"
2022-03-11 20:06:33 +00:00
"github.com/getsentry/sentry-go"
"github.com/spf13/viper"
)
2022-08-02 05:26:41 +00:00
var (
globalConfig Configuration
globalLock *sync.Mutex
2024-06-15 14:20:32 +00:00
//go:embed fermentord.toml
globalData []byte
2022-08-02 05:26:41 +00:00
)
2022-03-11 20:06:33 +00:00
2022-08-02 05:26:41 +00:00
func init() {
globalLock = &sync.Mutex{}
}
2022-03-11 20:06:33 +00:00
2024-06-15 14:20:32 +00:00
func Global() Configuration {
2022-08-02 05:26:41 +00:00
globalLock.Lock()
2024-06-15 14:20:32 +00:00
defer globalLock.Unlock()
return globalConfig
2022-03-11 20:06:33 +00:00
}
2022-08-02 18:59:27 +00:00
func Initialize() {
2022-08-02 05:26:41 +00:00
setDefaults()
2022-03-11 20:06:33 +00:00
viper.SetConfigName("fermentord")
viper.SetConfigType("toml")
2022-08-02 18:59:27 +00:00
}
func LoadConfiguration() Configuration {
globalLock.Lock()
defer globalLock.Unlock()
2022-03-11 20:06:33 +00:00
2024-06-15 14:20:32 +00:00
buf := bytes.NewBuffer(globalData)
if err := viper.ReadConfig(buf); err != nil {
panic(err)
}
if err := viper.MergeInConfig(); err != nil {
2022-03-11 20:06:33 +00:00
log.Printf("Error loading configuration: %v", err)
}
2024-06-15 14:20:32 +00:00
config := Configuration{}
if err := viper.Unmarshal(&config); err != nil {
2022-07-25 08:55:25 +00:00
sentry.CaptureException(err)
2022-03-11 20:06:33 +00:00
log.Fatal(err)
}
2024-06-15 14:20:32 +00:00
globalConfig = config
2022-08-02 18:59:27 +00:00
return globalConfig
2022-03-11 20:06:33 +00:00
}