使用AWS Lambda和Golang连接到AWS RDS PostgreSQL

时间:2018-06-18 11:07:43

标签: postgresql go aws-lambda amazon-rds

我正在尝试从Go中的lambda连接到AWS RDS PosgreSQL数据库。

authToken在日志中似乎很好。

creds := credentials.NewEnvCredentials()
authToken, err := rdsutils.BuildAuthToken("something.eu-west-3.rds.amazonaws.com", "eu-west-3", "Username", creds)

if err != nil {
    fmt.Println("Cannot create db auth token")
    return response.Status(500), err
}

// Create the DNS string for the DB connection
// // user:password@protocol(endpoint:port)/dbname?<params>
dnsStr := fmt.Sprintf("postgres://%s:%s@%s/%s?sslmode=verify-full",
    "Username", authToken, "something.eu-west-3.rds.amazonaws.com", "table_name",
)
db, err := sql.Open("postgres", dnsStr)

if err != nil {
    fmt.Println("Cannot open db")
    return response.Status(500), err
}

err = db.Ping()

if err != nil {
    fmt.Println("Cannot ping db")
    return response.Status(500), err
}

fmt.Println("Connection established")

我在db.Ping()和我收到的日志中有错误

Cannot ping db
dial tcp: address tcp/something.eu-west-3.rds.amazonaws.com: unknown port: OpError
null

我使用导入为pq

_ "github.com/lib/pq"

我尝试在主机之后的网址中添加默认端口5432,但没有结果。

我确定我错过了一个愚蠢的关键点,plz halp

1 个答案:

答案 0 :(得分:3)

当您手动创建连接URL时,您需要转义路径特殊变量:

dnsStr := fmt.Sprintf("postgres://%s:%s@%s/testdb",
    "rdsadmin", url.PathEscape(authToken), "something.eu-west-3.rds.amazonaws.com")

打印连接ping错误可能也很有用:

fmt.Printf("Cannot ping db: %s\n", err)