GO application failed to connect to local PostgreSQL database using environment variables in Windows.
After setting the environment variables using the windows command prompt
like the following:
set DATABASE_HOST=localhost
set DATABASE_USER=postgres
set DATABASE_PASSWORD=password
set DATABASE_NAME=db
set DATABASE_PORT=5432
The following command was tried to run the go application:
go run main.go
I get the following error:
←[0m←[31m[error] ←[0mfailed to initialize database, got error cannot parse `host= user= password=xxxxx dbname= port=`: invalid port (strconv.ParseUint: parsing "": invalid syntax)
panic: Failed to connect to database!
goroutine 1 [running]:
C:/Users/user/go/src/code/db.go:12 +0xb4
This is the code for the db.go
import (
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
func ConnectDatabase(dsn string) *gorm.DB {
database, err := gorm.Open(postgres.Open(dsn))
if err != nil {
panic("Failed to connect to database!")
}
return database
}
But when echo
command was tried it does return the correct value in the command prompt. Example echo %DATABASE_PORT%
command returns 5432
.
Note: main.go has the database migration related to code to initialize the database tables and schemas and works fine in Linux and Mac OS.