2020-03-18 14:45:55 +00:00
|
|
|
package config
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"io/ioutil"
|
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
|
|
|
|
"github.com/BurntSushi/toml"
|
2020-03-25 06:58:58 +00:00
|
|
|
"github.com/ghodss/yaml"
|
2020-03-18 14:45:55 +00:00
|
|
|
|
|
|
|
"github.com/caos/zitadel/internal/errors"
|
|
|
|
)
|
|
|
|
|
|
|
|
type ValidatableConfiguration interface {
|
|
|
|
Validate() error
|
|
|
|
}
|
|
|
|
|
|
|
|
type ReaderFunc func(data []byte, o interface{}) error
|
|
|
|
|
|
|
|
var (
|
2020-03-23 15:31:26 +00:00
|
|
|
JSONReader = json.Unmarshal
|
|
|
|
TOMLReader = toml.Unmarshal
|
2020-03-25 06:58:58 +00:00
|
|
|
YAMLReader = func(data []byte, o interface{}) error { return yaml.Unmarshal(data, o) }
|
2020-03-18 14:45:55 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// Read deserializes each config file to the target obj
|
|
|
|
// using a Reader (depending on file extension)
|
|
|
|
// env vars are replaced in the config file as well as the file path
|
|
|
|
func Read(obj interface{}, configFiles ...string) error {
|
|
|
|
for _, cf := range configFiles {
|
2020-03-23 15:31:26 +00:00
|
|
|
readerFunc, err := readerFuncForFile(cf)
|
2020-03-18 14:45:55 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2020-03-23 15:31:26 +00:00
|
|
|
if err := readConfigFile(readerFunc, cf, obj); err != nil {
|
2020-03-18 14:45:55 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if validatable, ok := obj.(ValidatableConfiguration); ok {
|
|
|
|
if err := validatable.Validate(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-03-23 15:31:26 +00:00
|
|
|
func readConfigFile(readerFunc ReaderFunc, configFile string, obj interface{}) error {
|
2020-03-18 14:45:55 +00:00
|
|
|
configFile = os.ExpandEnv(configFile)
|
|
|
|
|
|
|
|
configStr, err := ioutil.ReadFile(configFile)
|
|
|
|
if err != nil {
|
|
|
|
return errors.ThrowInternalf(err, "CONFI-nJk2a", "failed to read config file %s", configFile)
|
|
|
|
}
|
|
|
|
|
|
|
|
configStr = []byte(os.ExpandEnv(string(configStr)))
|
|
|
|
|
2020-03-23 15:31:26 +00:00
|
|
|
if err := readerFunc(configStr, obj); err != nil {
|
2020-03-18 14:45:55 +00:00
|
|
|
return errors.ThrowInternalf(err, "CONFI-2Mc3c", "error parse config file %s", configFile)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-03-23 15:31:26 +00:00
|
|
|
func readerFuncForFile(configFile string) (ReaderFunc, error) {
|
2020-03-18 14:45:55 +00:00
|
|
|
ext := filepath.Ext(configFile)
|
|
|
|
switch ext {
|
|
|
|
case ".yaml", ".yml":
|
|
|
|
return YAMLReader, nil
|
|
|
|
case ".json":
|
|
|
|
return JSONReader, nil
|
|
|
|
case ".toml":
|
|
|
|
return TOMLReader, nil
|
|
|
|
}
|
2020-05-13 12:22:29 +00:00
|
|
|
return nil, errors.ThrowUnimplementedf(nil, "CONFI-ZLk4u", "file extension (%s) not supported", ext)
|
2020-03-18 14:45:55 +00:00
|
|
|
}
|