oc-lib/tools/conf_loader.go

55 lines
1.7 KiB
Go
Raw Normal View History

2024-08-28 15:26:00 +02:00
package tools
import (
"strings"
"cloud.o-forge.io/core/oc-lib/logs"
"github.com/goraz/onion"
)
// GetConfLoader
// Get the configuration loader for the application
// Parameters:
// - AppName: string : the name of the application
// Returns:
// - *onion.Onion : the configuration loader
// The configuration loader will load the configuration from the following sources:
// - the environment variables with the prefix APPNAME_
// - the file /etc/oc/appname.json
// - the file ./appname.json
// The configuration loader will merge the configuration from the different sources
// The configuration loader will give priority to the environment variables
// The configuration loader will give priority to the local file over the default file
2024-09-02 15:21:16 +02:00
func GetConfLoader() *onion.Onion {
2024-08-28 15:26:00 +02:00
logger := logs.GetLogger()
2024-09-02 15:21:16 +02:00
AppName := logs.GetAppName()
2024-08-28 15:26:00 +02:00
EnvPrefix := strings.ToUpper(AppName[0:2]+AppName[3:]) + "_"
defaultConfigFile := "/etc/oc/" + AppName[0:2] + ".json"
localConfigFile := "./" + AppName[0:2] + ".json"
var configFile string
var o *onion.Onion
l3 := onion.NewEnvLayerPrefix("_", EnvPrefix)
l2, err := onion.NewFileLayer(localConfigFile, nil)
if err == nil {
logger.Info().Msg("Local config file found " + localConfigFile + ", overriding default file")
configFile = localConfigFile
}
l1, err := onion.NewFileLayer(defaultConfigFile, nil)
if err == nil {
logger.Info().Msg("Config file found : " + defaultConfigFile)
configFile = defaultConfigFile
}
if configFile == "" {
logger.Info().Msg("No config file found, using env")
o = onion.New(l3)
} else if l1 != nil && l2 != nil {
o = onion.New(l1, l2, l3)
} else if l1 == nil {
o = onion.New(l2, l3)
} else if l2 == nil {
o = onion.New(l1, l3)
}
return o
}