Cannot connect to RDS Postgres using Golang Gorm

时间:2019-03-19 14:38:56

标签: postgresql go amazon-rds go-gorm

I got this error when trying to connect to my RDS Postgres Endpoint

dial tcp 172.xx.xx.x:5432: i/o timeout panic: runtime error: invalid memory address or nil pointer dereference [signal SIGSEGV: segmentation violation code=0x1 addr=0x98 pc=0x1600d16]

Seems like there's some problem connecting to the endpoint

.Env file

DB_HOST=dbname.asdasddsa.ap-southeast-1.rds.amazonaws.com
DB_PORT=5432
DB_USER=username
DB_NAME=dbname
DB_PASSWORD=password

My database.go file

func InitDB() *gorm.DB {
    loadEnv() // For environment variables
    psqlInfo := fmt.Sprintf("host=%s user=%s dbname=%s sslmode=disable password=%s",
        os.Getenv("DB_HOST"),
        os.Getenv("DB_USER"),
        os.Getenv("DB_NAME"),
        os.Getenv("DB_PASSWORD"),
    )

    db, err := gorm.Open("postgres", psqlInfo)
    if err != nil {
        fmt.Println(err)
        return nil
    }
    fmt.Println("Connected to the Database")
    DB = db
    return DB
}

Do i need to configure anything in my RDS AWS? I followed this article

https://aws.amazon.com/getting-started/tutorials/create-connect-postgresql-db/

and followed the exact steps for the configuration

Regards,

1 个答案:

答案 0 :(得分:0)

我正在使用此功能连接到RDS上的postgres数据库

package database

import (
    "fmt"

    "github.com/jinzhu/gorm"
    config "github.com/spf13/viper"
)

func Connect() (*gorm.DB, error) {
    return gorm.Open(
        "postgres",
        fmt.Sprintf(
            "host=%s port=%s user=%s dbname=%s password=%s",
            config.GetString("postgres.host"),
            config.GetString("postgres.port"),
            config.GetString("postgres.user"),
            config.GetString("postgres.dbname"),
            config.GetString("postgres.password"),              
        ),
    )
}

在运行它之前,请检查您是否有权访问RDS数据库。 您可以在安全组规则下从AWS控制台-> RDS->数据库->-> [向下滚动]检查是否有权访问数据库 您可以查看是否已添加对安全组的访问权限以从网络访问数据库。

您可以在此处了解有关安全组的更多信息 https://docs.aws.amazon.com/vpc/latest/userguide/VPC_SecurityGroups.html#VPCSecurityGroups