Last active
May 4, 2019 10:55
-
-
Save linux08/1bf810bb5d5561dda61123980989c36f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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