Skip to content

Instantly share code, notes, and snippets.

@adigunhammedolalekan
Created May 3, 2018 11:49
Show Gist options
  • Save adigunhammedolalekan/d65145512cb1de55e40d74a37fe34f5a to your computer and use it in GitHub Desktop.
Save adigunhammedolalekan/d65145512cb1de55e40d74a37fe34f5a to your computer and use it in GitHub Desktop.
Connect to a postgresql database using GORM
package models
import (
_ "github.com/jinzhu/gorm/dialects/postgres"
"github.com/jinzhu/gorm"
"os"
"github.com/joho/godotenv"
"fmt"
)
var db *gorm.DB //database
func init() {
e := godotenv.Load() //Load .env file
if e != nil {
fmt.Print(e)
}
username := os.Getenv("db_user")
password := os.Getenv("db_pass")
dbName := os.Getenv("db_name")
dbHost := os.Getenv("db_host")
dbUri := fmt.Sprintf("host=%s user=%s dbname=%s sslmode=disable password=%s", dbHost, username, dbName, password) //Build connection string
fmt.Println(dbUri)
conn, err := gorm.Open("postgres", dbUri)
if err != nil {
fmt.Print(err)
}
db = conn
db.Debug().AutoMigrate(&Account{}, &Contact{}) //Database migration
}
//returns a handle to the DB object
func GetDB() *gorm.DB {
return db
}
@Yuideg
Copy link

Yuideg commented May 14, 2021

it is nice!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment