Home > Net >  How to load both .env file and the os environment variables in golang
How to load both .env file and the os environment variables in golang

Time:09-03

err := godotenv.Load(".env") if err != nil { panic(err.Error()) }

shell := os.Getenv("SHELL") fmt.Println(shell)

I set the SHELL=/bin/zsh in my .env file but it seems the os first look for the given key in the os environment variable list and then It checks the .env file . is there a way to separate these two ?

CodePudding user response:

Yes there is a way to solve this problem . the github.com/joho/godotenv has a function called Read() . you can load your .env file into a map data structure .

envFile, _ := godotenv.Read(".env")

envFileShell = envFile["SHELL"]
fmt.Println(envFileShell) // will be /bin/zsh (what you set in .env file)

osShell := os.Getenv("SHELL") 
fmt.Println(osShell) // will be whatever it is set in your operating system 
  •  Tags:  
  • go
  • Related