Advertisement
Guest User

Untitled

a guest
May 14th, 2019
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.98 KB | None | 0 0
  1. package utils
  2.  
  3. import (
  4. "auth/models"
  5. "fmt"
  6. "log"
  7. "os"
  8.  
  9. "github.com/jinzhu/gorm"
  10. _ "github.com/jinzhu/gorm/dialects/postgres" //Gorm postgres dialect interface
  11. "github.com/joho/godotenv"
  12. )
  13.  
  14. //ConnectDB function: Make database connection
  15. func ConnectDB() *gorm.DB {
  16.  
  17. //Load environmenatal variables
  18. err := godotenv.Load()
  19.  
  20. if err != nil {
  21. log.Fatal("Error loading .env file")
  22. }
  23.  
  24. username := os.Getenv("databaseUser")
  25. password := os.Getenv("databasePassword")
  26. databaseName := os.Getenv("databaseName")
  27. databaseHost := os.Getenv("databaseHost")
  28.  
  29. //Define DB connection string
  30. dbURI := fmt.Sprintf("host=%s user=%s dbname=%s sslmode=disable password=%s", databaseHost, username, databaseName, password)
  31.  
  32. //connect to db URI
  33. db, err := gorm.Open("postgres", dbURI)
  34.  
  35. if err != nil {
  36. fmt.Println("error", err)
  37. panic(err)
  38. }
  39. // close db when not in use
  40. defer db.Close()
  41.  
  42. // Migrate the schema
  43. db.AutoMigrate(
  44. &models.User{})
  45.  
  46. fmt.Println("Successfully connected!", db)
  47. return db
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement