Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

dotenv config file does not behave like environment variables #814

Open
soedar opened this issue Dec 17, 2019 · 1 comment
Open

dotenv config file does not behave like environment variables #814

soedar opened this issue Dec 17, 2019 · 1 comment

Comments

@soedar
Copy link

soedar commented Dec 17, 2019

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?

@sagikazarmark
Copy link
Collaborator

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).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants