-5

I got my database settings in .env file. Whenever I write source .env it doesn't work, I have no clue why, in other apps it works fine. I am getting this error now

`` is not officially supported, running under compatibility mode.
2021/04/15 16:57:03 sql: unknown driver "" (forgotten import?)
exit status 1

My imports:

    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/postgres"
    dialect := os.Getenv("DIALECT")
    host := os.Getenv("HOST")
    dbPort := os.Getenv("DBPORT")
    user := os.Getenv("USER")
    dbName := os.Getenv("NAME")
    password := os.Getenv("PASSWORD")

    dbURI := fmt.Sprintf("host=%s user=%s dbname=%s password=%s port=%s", host, user, dbName, password, dbPort)

It runs fine, whenever I provide settings such as dialect := "postgres" etc. But it won't work with env file, why my app is not finding it?

Folder structure

api/
   .env
   go.mod
   go.sum
   main.go
Dave
  • 1
  • 1
  • 9
  • 38
  • 5
    "Whenever I write source .env it doesn't work" meaning what? Do you get an error? What's in that file? This is a basic Linux shell question, not a Go question - your issue isn't Go, it's just setting env vars using a bash script. – Adrian Apr 15 '21 at 15:24
  • Maybe you have to [add export before each variable](https://stackoverflow.com/a/19331521) in the sourced env file – xarantolus Apr 15 '21 at 15:27
  • A .env file doesn't magically populate you environment and neither is "picked up" magically by your Go code. .env files and their magic have no place in the unix world and Go. – Volker Apr 15 '21 at 16:13
  • I found that in your particular case, prefixing each variable in the .env file using 'export' resolves the problem. If you are still experiencing this problem, try this ``` export DIALECT="ADD_VALUE" export HOST="ADD_VALUE" export DBPORT="ADD_VALUE" export USER="ADD_VALUE" export DBNAME="ADD_VALUE" export PASSWORD="ADD_VALUE" ``` ALSO (very important) make sure you execute "source .env" on the bash terminal before you execute "go run main.go". This is how the variables will be loaded into your environment – mainas Aug 02 '23 at 04:28

1 Answers1

1

Clearly, the variable is not being set in the environment space prior to the execution of the app. You can test this yourself by viewing your set environment variables prior to running the app. os.getenv() will also not source .env files for you, so you either need to do this manually, or use a library that will do this for you (e.g. godotenv).

Paul Mundt
  • 459
  • 6
  • 9