godotenv icon indicating copy to clipboard operation
godotenv copied to clipboard

.env: no such file or directory

Open chihao10711 opened this issue 1 year ago • 5 comments

When I use go run it works well. However, when using go build couldn't be found .env. Please help me with this?

chihao10711 avatar Aug 07 '23 08:08 chihao10711

I just tried

// imports

func main() {
  err := godotenv.Load()
  if err != nil {
    log.Fatal("Error loading .env file")
  }
}

and then ran go run main.go and go build main.go && ./main without any issues.

Could you provide some more details?

henrikac avatar Aug 08 '23 18:08 henrikac

When I use go run it works well. However, when using go build couldn't be found .env. Please help me with this?

try this : godotenv.Load("full_path")

go clean go build

arieansyah avatar Aug 29 '23 10:08 arieansyah

It looks like this is as stale issue that can be closed?

cc/ @chihao10711

coolaj86 avatar Oct 17 '23 17:10 coolaj86

so my expectation prior to reading the code would be that it would look for .env files in the list you gave it, loading the ones that exist, so that you could give it a list and it would load what it found. The reality is that it stops at the first missing file, due to a file not found error being treated as a hard error. This is a design decision, but is it what the user wants? I ended up writing a function to filter the list to only existing files before passing to load, but of course this won't work with autoload. I look in the current directory for .env.${ENVIRONMENT}, .env, then $(dirname ${GOMOD}) for the same.

Basically the Load() function here works like the ruby Load!() which I wouldn't expect given the project goal.

It would be a breaking API change for the folks who've installed and now expect this behavior though, so maybe you just want to add a function to trim down the file list to only existing ones which will then effectively make this work like Load on the result of that function.

beiriannydd avatar Nov 02 '23 19:11 beiriannydd

@beiriannydd Even I have similar requirements to try loading all files found and return an error at the end if any errors occur along with the ability to look at the root git directory, also at the go mod directory level.

Probably if you have similar requirements, you can utilise this

gwthm-in avatar Dec 16 '23 05:12 gwthm-in