Skip to content

Can I tell viper.Unmarshal to take environment variables into account? #212

Closed
@aeneasr

Description

This is my viper config:

    if cfgFile != "" {
        // enable ability to specify config file via flag
        viper.SetConfigFile(cfgFile)
    }

    path := absPathify("$HOME")
    if _, err := os.Stat(filepath.Join(path, ".hydra.yml")); err != nil {
        _, _ = os.Create(filepath.Join(path, ".hydra.yml"))
    }

    viper.SetConfigType("yaml")
    viper.SetConfigName(".hydra") // name of config file (without extension)
    viper.AddConfigPath("$HOME")  // adding home directory as first search path
    viper.AutomaticEnv()          // read in environment variables that match

    // If a config file is found, read it in.
    if err := viper.ReadInConfig(); err != nil {
        fmt.Printf(`Config file not found because "%s"`, err)
        fmt.Println("")
    }

I also have a bunch of environment varibales, like CLIENT_ID or DATABASE_URL. Right now I'm setting those via:

    if databaseURL, ok := viper.Get("DATABASE_URL").(string); ok {
        c.DatabaseURL = databaseURL
    }

Is it possible to tell viper.Unmarshal to use the environment variables in addition to the config file?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions