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 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图