spf13 / viper

Go configuration with fangs
MIT License
27.19k stars 2.02k forks source link

Issue reading in .env file #1102

Open dtrinh100 opened 3 years ago

dtrinh100 commented 3 years ago

Expected behavior (what you expected to happen):

For it to read in the config from the .env file and map it to the struct.

Actual behavior (what actually happened):

I get the following error: While parsing config: lineapp:doesn't match format

Repl.it link:

Code reproducing the issue:

.env:

APP_ENVIRONMENT=development

config.go:

type Configs struct {
    AppEnvironment           string `mapstructure:"APP_ENVIRONMENT"`
}

main.go

var configs config.Configs
viper.SetConfigType("env") // REQUIRED if the config file does not have the extension in the name
viper.AddConfigPath(".")               // optionally look for config in the working directory
err := viper.ReadInConfig() // Find and read the config file
if err != nil { // Handle errors reading the config file
    panic(fmt.Errorf("Fatal error config file: %s \n", err))
}
err := viper.Unmarshal(&configs)
if err != nil {
    panic(err)
}

Environment:

Anything else we should know?:

github-actions[bot] commented 3 years ago

👋 Thanks for reporting!

A maintainer will take a look at your issue shortly. 👀

In the meantime: We are working on Viper v2 and we would love to hear your thoughts about what you like or don't like about Viper, so we can improve or fix those issues.

⏰ If you have a couple minutes, please take some time and share your thoughts: https://forms.gle/R6faU74qPRPAzchZ9

📣 If you've already given us your feedback, you can still help by spreading the news, either by sharing the above link or telling people about this on Twitter:

https://twitter.com/sagikazarmark/status/1306904078967074816

Thank you! ❤️

xwjdsh commented 3 years ago

I tried your example, just add one line and everything will be fine.

viper.SetConfigType("env")
viper.AddConfigPath(".")
+ viper.SetConfigFile(".env")
kchugalinskiy commented 3 years ago
func New() *Viper {
...
    v.configName = "config"

this is the root cause of your issue. by specifying extension only viper assumes you're searching for config.env file. so use SetConfigFile as specified above please