From 4144844f4387a6a3b22babfc2cc92095f514735e Mon Sep 17 00:00:00 2001 From: qwqcode Date: Fri, 1 Sep 2023 19:25:48 +0800 Subject: [PATCH] feat(config): support load env variables as config --- internal/config/base.go | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/internal/config/base.go b/internal/config/base.go index 97a62b922..53199b3bd 100644 --- a/internal/config/base.go +++ b/internal/config/base.go @@ -11,6 +11,7 @@ import ( "github.com/ArtalkJS/Artalk/internal/utils" "github.com/knadh/koanf" "github.com/knadh/koanf/parsers/yaml" + "github.com/knadh/koanf/providers/env" "github.com/knadh/koanf/providers/file" ) @@ -29,6 +30,18 @@ func NewFromFile(cfgFile string) (*Config, error) { return nil, fmt.Errorf("config file read error: %w", err) } + // load environment variables and merge into the loaded config + const envPrefix = "ATK_" + if err := kf.Load(env.Provider(envPrefix, ".", func(s string) string { + // FOO__BAR -> foo_bar to handle dash in config names + s = strings.ToLower(strings.TrimPrefix(s, envPrefix)) + s = strings.ReplaceAll(s, "__", "-") + s = strings.ReplaceAll(s, "_", ".") + return strings.ReplaceAll(s, "-", "_") + }), nil); err != nil { + return nil, fmt.Errorf("config environment variable parse error: %w", err) + } + // create new config instance conf := &Config{ cfgFile: cfgFile,