Home > OS >  How do I connect to postgresql with gorm?
How do I connect to postgresql with gorm?

Time:11-09

How do I connect to postgresql with gorm? (FATAL: password authentication failed for user "postgres" (SQLSTATE 28P01))

package model

import (
    "gorm.io/driver/postgres"
    "gorm.io/gorm"
)

var db *gorm.DB

func init() {
    var err error
    dsn := "host=localhost user=postgres dbname=postgres port=5432 sslmode=disable TimeZone=Asia/Tokyo"
    db, err =  gorm.Open(postgres.Open(dsn), &gorm.Config{})
    if err != nil {
      panic("failed to connect database")
    }
    db.AutoMigrate(&User{})
    db.AutoMigrate(&Todo{})
}

CodePudding user response:

you can try this instead : Use Sprintf to declare dsn

host := "localhost"
user := "postgres"
password := ""
dbname := "DBNAME"
port := "5432"

dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%s sslmode=disable",
    host, user, password, dbname, port)
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{
    SkipDefaultTransaction: true,
})
if err != nil {
    panic(err)
}

and check the database connection use :

func TestConnect(t *testing.T) {
//your DB setup function

}

  •  Tags:  
  • go
  • Related