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:""}
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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:""}