Guest User

Untitled

a guest
May 10th, 2019
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.10 KB | None | 0 0
  1. package common
  2.  
  3. import (
  4. "github.com/deissh/api.micro/helpers"
  5. "github.com/deissh/api.micro/models"
  6. "github.com/jinzhu/gorm"
  7. _ "github.com/jinzhu/gorm/dialects/postgres"
  8. "github.com/labstack/gommon/log"
  9. )
  10.  
  11. type Database struct {
  12. *gorm.DB
  13. }
  14.  
  15. var DB *gorm.DB
  16.  
  17. // Opening a database and save the reference to `Database` struct.
  18. func Init() *gorm.DB {
  19. host := helpers.GetEnv("DB_HOST", "127.0.0.1")
  20. user := helpers.GetEnv("DB_USER", "zikal")
  21. dbName := helpers.GetEnv("DB_NAME", "microapi")
  22. psw := helpers.GetEnv("DB_PSW", "123")
  23.  
  24. db, err := gorm.Open("postgres", "sslmode=disable host="+host+" user="+user+" dbname="+dbName+" password="+psw)
  25. if err != nil {
  26. log.Panic(err)
  27. }
  28. db.DB().SetMaxIdleConns(10)
  29. //db.LogMode(true)
  30. DB = db
  31.  
  32. log.Info("Database connected")
  33. return DB
  34. }
  35.  
  36. // Migrate all needed tables
  37. func Migrate() {
  38. // create tables if not exist
  39. // todo: add auto migration
  40. DB.AutoMigrate(&models.User{},&models.News{})
  41. }
  42.  
  43. // Using this function to get a connection, you can create your connection pool here.
  44. //func GetDB() *gorm.DB {
  45. // return DB
  46. //}
Add Comment
Please, Sign In to add comment