在Heroku上使用Go和Postgres时出现了连接被拒绝的问题。

huangapple go评论87阅读模式
英文:

Connection refused with Go + Postgres on Heroku

问题

我正在尝试使用Go连接到Heroku的Postgres数据库。在本地一切正常。

我在Heroku上收到的错误是dial tcp 127.0.0.1:5432: connection refused

我已经确认通过Heroku的命令行工具可以连接到数据库,并确认数据库URL配置正确。代码很清晰,所以我想知道是否存在更低级别的问题。

代码很简单:

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
}

我已经导入了github.com/lib/pq。Go版本是1.1.2。

英文:

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.

答案1

得分: 11

Heroku + Go对连接字符串有一些特殊要求。URL格式似乎不允许指定sslmode=require,而Heroku坚持要求这样做。

修改后的版本使用pq将URL解析为传统的Postgres连接字符串,并附加了参数:

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
}
英文:

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
}

huangapple
  • 本文由 发表于 2013年10月4日 12:52:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/19173460.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定