0

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.

Valhala
  • 21
  • 4
  • 2
    What is the value of `dsn`? It should look something like `host=localhost user=postgres password=password dbname=db port=5432 sslmode=disable TimeZone=Asia/Shanghai`. Maybe change panic to `panic(fmt.Sprintf("Failed to connect to database - %s", dsn))` (but note that this may dump a password to logs so revert when issue fixed). – Brits Feb 17 '22 at 22:36
  • 1
    What is reading in the environment variable for `DATABASE_PORT`? – mikequentel Feb 17 '22 at 23:27
  • The value of dsn is weirdly ` host= user= password= dbname= port=` so panic returns `panic: Failed to connect to database - host= user= password= dbname= port=` @Brits. The value of `DATABASE_PORT` is set to 5432 @mikequentel – Valhala Feb 17 '22 at 23:41
  • 2
    The issue is not in the code you have shown us. You need to look at how `dsn` is being set (somewhere you should be accessing the environmental variables). Also please note that setting variables in one terminal window will have no impact on others... – Brits Feb 18 '22 at 00:02
  • You seem to think that if set, these environment variables will be automatically consumed by gorm, but I see no documentation that supports that belief. I think you have to do that yourself – erik258 Feb 18 '22 at 03:19

0 Answers0