Guest User

Untitled

a guest
May 9th, 2018
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.77 KB | None | 0 0
  1. package models
  2.  
  3. import (
  4. _ "github.com/jinzhu/gorm/dialects/postgres"
  5. "github.com/jinzhu/gorm"
  6. "os"
  7. "github.com/joho/godotenv"
  8. "fmt"
  9. )
  10.  
  11. var db *gorm.DB //database
  12.  
  13. func init() {
  14.  
  15. e := godotenv.Load() //Load .env file
  16. if e != nil {
  17. fmt.Print(e)
  18. }
  19.  
  20. username := os.Getenv("db_user")
  21. password := os.Getenv("db_pass")
  22. dbName := os.Getenv("db_name")
  23. dbHost := os.Getenv("db_host")
  24.  
  25.  
  26. dbUri := fmt.Sprintf("host=%s user=%s dbname=%s sslmode=disable password=%s", dbHost, username, dbName, password) //Build connection string
  27. fmt.Println(dbUri)
  28.  
  29. conn, err := gorm.Open("postgres", dbUri)
  30. if err != nil {
  31. fmt.Print(err)
  32. }
  33.  
  34. db = conn
  35. db.Debug().AutoMigrate(&Account{}, &Contact{}) //Database migration
  36. }
  37.  
  38. //returns a handle to the DB object
  39. func GetDB() *gorm.DB {
  40. return db
  41. }
Add Comment
Please, Sign In to add comment