Viper: dotenv config file does not behave like environment variables

Created on 17 Dec 2019  路  1Comment  路  Source: spf13/viper

A short example to briefly illustrate the problem:

package main

import (
    "bytes"
    "fmt"

    "github.com/spf13/viper"
)

func main() {
    dotenvExample := []byte(`DATABASE_PORT=5432`)

    viper.SetConfigType("env")
    viper.ReadConfig(bytes.NewBuffer(dotenvExample))
    viper.BindEnv("database.port", "DATABASE_PORT")

    // I would expect 5432, but got <nil>
    fmt.Println(viper.Get("database.port"))
}

A cursory look at the source suggests that the v.env variable stores the mapping of key => ENV_VAR (i.e. database.port => DATABASE_PORT). A fast way to resolve this would be to search through the v.env variable when marshaling dotenv config file, and assign the v.env's key if the value matches.

However, doing this way introduce an ordering constraint: viper.BindEnv must happen before viper.ReadConfig, otherwise the v.env would not be populated correctly then.

Any suggestions on what's the best way to move forward on this?

Most helpful comment

Personally, I would probably just load the dotenv file contents as environment variables. It's a simple solution and does not require huge changes with very little benefit in Viper.

I'm not sure I agree with the assumption that a dotenv file (parsed as file) should behave exactly like environment variables.

It's a file format from Viper's point of view, which means keys could be normalized (eg. using the string replacer), but binding is probably out of scope.

That being said, this could be a use case considered in a next version (#772) of the library.

For now, I would just set those variables as env vars from the file (pretty sure there are libraries for that).

>All comments

Personally, I would probably just load the dotenv file contents as environment variables. It's a simple solution and does not require huge changes with very little benefit in Viper.

I'm not sure I agree with the assumption that a dotenv file (parsed as file) should behave exactly like environment variables.

It's a file format from Viper's point of view, which means keys could be normalized (eg. using the string replacer), but binding is probably out of scope.

That being said, this could be a use case considered in a next version (#772) of the library.

For now, I would just set those variables as env vars from the file (pretty sure there are libraries for that).

Was this page helpful?
0 / 5 - 0 ratings