Skip to content

Instantly share code, notes, and snippets.

@linux08
Last active May 4, 2019 10:55
Show Gist options
  • Save linux08/1bf810bb5d5561dda61123980989c36f to your computer and use it in GitHub Desktop.
Save linux08/1bf810bb5d5561dda61123980989c36f to your computer and use it in GitHub Desktop.
package utils
import (
"auth/models"
"fmt"
"log"
"os"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres" //Gorm postgres dialect interface
"github.com/joho/godotenv"
)
//ConnectDB function: Make database connection
func ConnectDB() *gorm.DB {
//Load environmenatal variables
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
username := os.Getenv("databaseUser")
password := os.Getenv("databasePassword")
databaseName := os.Getenv("databaseName")
databaseHost := os.Getenv("databaseHost")
//Define DB connection string
dbURI := fmt.Sprintf("host=%s user=%s dbname=%s sslmode=disable password=%s", databaseHost, username, databaseName, password)
//connect to db URI
db, err := gorm.Open("postgres", dbURI)
if err != nil {
fmt.Println("error", err)
panic(err)
}
// close db when not in use
defer db.Close()
// Migrate the schema
db.AutoMigrate(
&models.User{})
fmt.Println("Successfully connected!", db)
return db
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment