doudouba4520 2019-03-19 14:38
浏览 341

无法使用Golang Gorm连接到RDS Postgres

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条回答 默认 最新

  • dsqe46004 2019-04-02 11:15
    关注

    I am using this function to connect to my postgres database on RDS

    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"),              
            ),
        )
    }
    

    Please check if you have access to your RDS database before running this. You can check if you have access to the database from AWS console -> RDS -> database -> -> [scroll down] under Security group rules You can see if you have added access to the security group to access your database from your network.

    You can learn more about security groups here https://docs.aws.amazon.com/vpc/latest/userguide/VPC_SecurityGroups.html#VPCSecurityGroups

    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?