Open HeathNaylor opened 8 years ago
While .env in the project root is the default, you don't have to be constrained, both examples below are 100% legit
= godotenv.Load("somerandomfile") = godotenv.Load("filenumberone.env", "filenumbertwo.env")
The above is in the readme and should do the job.
The above is in the readme and should do the job.
err := godotenv.Load("~/www/site/myweb/.env")
if err != nil {
log.Fatal("Error loading .env file")
}
this doesn't work
Try using
err := godotenv.Load(path.Join(os.Getenv("HOME"),"www/site/myweb/.env"))
if err != nil {
log.Fatal("Error loading .env file")
}
@Sjeanpierre thanks that works
it's the same as:
err := godotenv.Load("/home/user1/www/site/myweb/.env")
if err != nil {
log.Fatal("Error loading .env file")
}
which I though I tried before, but the example you have is better, it will result in much less rewrite.
In case anyone else might be looking for this in 2020. I found a great solution, which is to build project path dynamically :
package config
import (
"path/filepath"
"runtime"
)
var (
// Get current file full path from runtime
_, b, _, _ = runtime.Caller(0)
// Root folder of this project
ProjectRootPath = filepath.Join(filepath.Dir(b), "../")
)
Than call it with :
godotenv.Load(config.ProjectRootPath + "/.env")
First, get project base directory:
func IsFile(filename string) bool {
info, err := os.Stat(filename)
if os.IsNotExist(err) {
return false
}
return !info.IsDir()
}
func FindDir(filename string) string {
dir, _ := os.Getwd()
for !IsFile(path.Join(dir, filename)) {
pdir := path.Dir(dir)
if pdir == dir {
return ""
}
dir = pdir
}
return dir
}
var BaseDir = FindDir("go.mod")
and then load .env file:
func init() {
if BaseDir == "" {
log.Fatalln("Please use `go mod init` to create project.")
return
}
envFile := path.Join(BaseDir, ".env")
err := godotenv.Load(envFile)
if err != nil {
log.Fatalf("Failed to load %s: %+v\n", envFile, err)
return
}
// ....
}
I needed to make reference to ./src/.env
I used os.Executable
but it returns /private/var/folder/1g....
.
I don't know what it refers to as I don't have a single reference to this directory when I run go env
.
But it worked when I ran my containerized app (from a scratch dockerfile).
The solution for me was to use curDir, err := os.Getwd()
then loadErr := godotenv.Load(curDir + "/.env")
.
Don't know if it's the "by the books" way of dealing with a "local dev conf" and a "containerized local dev conf" but up to know, it's working.
When I am working on my project I am happy having my .env in the root of my git repo, however, when I run
go install
which points to/srv
in myGOPATH
environmental variable I want it to read the .env from/srv/.env
. Right now I am just sym linking and this works fine, but feels a little hacky. Thoughts?