Environment variable does not overwrite yaml config
alexbunt opened this issue · comments
Describe the bug
I am trying to have environment variables overwrite something set in my yaml config file however the environment variable does not get set
To Reproduce
Steps / breaking unit test / example to reproduce the behavior
main.go:
package main
import (
"fmt"
"log"
"strings"
"github.com/knadh/koanf/parsers/yaml"
"github.com/knadh/koanf/providers/env"
"github.com/knadh/koanf/providers/file"
"github.com/knadh/koanf/v2"
)
type Config struct {
DB DBConfig `koanf:"db"`
Key string `koanf:"key"`
}
type DBConfig struct {
Host string `koanf:"host"`
}
func loadConfig(path string) (config Config, err error) {
k := koanf.New(".")
if err = k.Load(file.Provider("config.yml"), yaml.Parser()); err != nil {
return
}
fmt.Println(k.String("db.host"))
k.Load(env.Provider("MYVAR_", ".", func(s string) string {
return strings.Replace(strings.ToLower(
strings.TrimPrefix(s, "MYVAR_")), "_", ".", -1)
}), nil)
fmt.Println(k.String("db.host"))
k.Unmarshal("", &config)
return
}
func main() {
config, err := loadConfig(".")
if err != nil {
log.Fatal("cannot load config:", err)
}
You can see in the loadConfig function I have it reading a yaml file, echoing the DB.Host, then reading the env vars, then echoing it again.
config.yml:
db:
host: localhost
Expected behavior
I set the variable then run the program:
MYVAR_DB_HOST=db_server
go run main.go
// expected output
localhost
db_server - as it would change to the env var
// actual output
localhost
localhost - it did not read the env var
Please provide the following information):
- OS: Linux
- Koanf Version v2
Additional context
I'm aware this is likely me and not a bug :)
You're missing export
. Should be export MYVAR_DB_HOST=db_server
The program you shared above works.
$ export MYVAR_DB_HOST=xxxx
$ go run main.go
localhost
xxxx
Doh, of course. Thank you