Select Git revision
struct.go 3.32 KiB
package config
import (
"regexp"
"gitlab.com/uafrica/go-utils/errors"
"gitlab.com/uafrica/go-utils/logger"
"gitlab.com/uafrica/go-utils/string_utils"
"gitlab.com/uafrica/go-utils/struct_utils"
)
var (
prefixStructs = map[string]interface{}{}
)
func LoadEnv(prefix string, configStructPtr interface{}) error {
return Load(prefix, configStructPtr, string_utils.EnvironmentKeyReader())
}
func Load(prefix string, configStructPtr interface{}, keyReader string_utils.KeyReader) error {
if !prefixRegex.MatchString(prefix) {
return errors.Errorf("config(%s) invalid prefix", prefix)
}
//store before load in case it fails to be still part of docs
prefixStructs[prefix] = configStructPtr
//read os.Getenv() or other reader...
nv := struct_utils.NamedValuesFromReader(prefix, keyReader)
logger.Debugf("nv: %+v", nv)
//parse into struct
unused, err := struct_utils.UnmarshalNamedValues(nv, configStructPtr)
if err != nil {
return errors.Wrapf(err, "config(%s) cannot load", prefix)
}
if len(unused) > 0 {
//we still use os.Getenv() elsewhere, so some variables may not be in the struct
//e.g. AUDIT_QUEUE_URL is read from queues/sqs/producer which match config(prefix="AUDIT")
//so we cannot yet fail here, which we should, because config setting not used is often
//a reason for errors, when we try to configure something, then it does not work, and
//we cannot figure out why, but the value we did set, might just be misspelled etc.
//so, for now - do not fail here, just report the unused values
logger.Warnf("Note unused env (might be used elsewhere) for config(%s): %+v", prefix, unused)
//return errors.Errorf("config(%s): unknown %+v", prefix, unused)
}
if validator, ok := configStructPtr.(Validator); ok {
if err := validator.Validate(); err != nil {
return errors.Wrapf(err, "config(%s) is invalid", prefix)
}
}
return nil
}
func LoadRedis(prefix string, configStructPtr interface{}) error {
if !prefixRegex.MatchString(prefix) {
return errors.Errorf("config(%s) invalid prefix", prefix)
}
//store before load in case it fails to be still part of docs
prefixStructs[prefix] = configStructPtr
//read os.Getenv()
nv := struct_utils.NamedValuesFromEnv(prefix)
//parse into struct
unused, err := struct_utils.UnmarshalNamedValues(nv, configStructPtr)
if err != nil {
return errors.Wrapf(err, "config(%s) cannot load", prefix)