Skip to content

Can Viper read env file naming like .env.[mode](e.g. .env.local, .env.production, etc.)? #1496

Closed Answered by keelus
100gle asked this question in Q&A
Discussion options

You must be logged in to vote

It supports it. You have to specify the type first, and then the file name:

func main() {
	viper.SetConfigType("env")
	viper.SetConfigFile(".env.local")

	if err := viper.ReadInConfig(); err != nil {
		fmt.Println(".env.local not found. Trying with .env ...")

		viper.SetConfigFile(".env")
		if err2 := viper.ReadInConfig(); err2 != nil {
			panic("Error reading the .env file")
		} else {
			fmt.Println(".env loaded")
		}
	} else {
		fmt.Println(".env.local loaded")
	}

	// Handle keys
}

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@100gle
Comment options

Answer selected by 100gle
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants