DEV Community

Discussion on: Load config from file & environment variables in Golang with Viper

Collapse
 
vaskir profile image
Vasily Kirichenko

I'm trying to unmarshal an environment variable into a struct field, just as you show in this article, but I've stuck:

package main

import (
"fmt"
"github.com/spf13/viper"
"log"
"os"
)

type Config struct {
EXE_PATH string
}

func main() {
if err := os.Setenv("EXE_PATH", "exe path from env"); err != nil {
log.Fatal(err)
}
viper.AddConfigPath(".")
viper.SetConfigType("yaml")
viper.AutomaticEnv()
if err := viper.ReadInConfig(); err != nil {
log.Fatal(err)
}
var cfg Config
if err := viper.Unmarshal(&cfg); err != nil {
log.Fatal(err)
}
fmt.Printf("EXE_PATH: %v\n", viper.Get("EXE_PATH"))
fmt.Printf("%#v\n", cfg)
}

output:

EXE_PATH: exe path from env
main.Config{EXE_PATH:""}