Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connection refused with Go + Postgres on Heroku

I am trying to connect to Heroku's Postgres using a Go. All is working fine locally.

The error I am receiving on Heroku is dial tcp 127.0.0.1:5432: connection refused.

I've confirmed my ability to connect to the database via psql on heroku's command line, and have confirmed that the database url config is correct. The code is clear enough, so I wonder if there is a lower-level problem.

The code is straightforward enough:

import (
    "database/sql"
    "github.com/coopernurse/gorp"
    _ "github.com/lib/pq"
    "os"
)

func openDb() *sql.DB {
    connection := os.Getenv("DATABASE_URL")

    db, err := sql.Open("postgres", connection)
    if err != nil {
        log.Println(err)
    }

    return db
}

...and am importing github.com/lib/pq. Go version is 1.1.2.

like image 956
Matt Sherman Avatar asked Oct 04 '13 04:10

Matt Sherman


1 Answers

Heroku + Go is pretty particular about the connection strings. The URL-style doesn't seem to allow specification of sslmode=require, which Heroku insists upon.

The modified version uses pq to parse the URL into a traditional Postgres connection string, and appends the parameter:

import (
    "database/sql"
    "github.com/lib/pq"
    "os"
)

func openDb() *sql.DB {
    url := os.Getenv("DATABASE_URL")
    connection, _ := pq.ParseURL(url)
    connection += " sslmode=require"

    db, err := sql.Open("postgres", connection)
    if err != nil {
        log.Println(err)
    }

    return db
}
like image 79
Matt Sherman Avatar answered Oct 12 '22 01:10

Matt Sherman