Guest User

Untitled

a guest
Jan 16th, 2018
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.13 KB | None | 0 0
  1. package entity
  2.  
  3. import (
  4. "fmt"
  5. "log"
  6. "os"
  7.  
  8. "github.com/jinzhu/gorm"
  9. _ "github.com/jinzhu/gorm/dialects/postgres"
  10. _ "github.com/jinzhu/gorm/dialects/sqlite"
  11. )
  12.  
  13. // Session is a struct that contains a pointer to a GORM database. To create a new session, without passing one around, we rely on envrionment variables.
  14. // Creating a new entity is as easy as
  15. type Session struct {
  16. DB *gorm.DB
  17. }
  18.  
  19. // NewSession uses envrionment variables to create a new services to connect to a GORM database.
  20. // if the APP_ENV is set to testing, an in-memory database (sqlite) will be used for easy testing.
  21. func NewSession() *Session {
  22. switch os.Getenv("APP_ENV") {
  23. case "testing":
  24. db, err := gorm.Open("sqlite", ":memory")
  25. if err != nil {
  26. log.Fatal(err)
  27. }
  28. return &Session{DB: db}
  29. default:
  30. db, err := gorm.Open("postgres", fmt.Sprintf(
  31. "host=%v user=%v dbname=%v sslmode=%v password=%v",
  32. os.Getenv("DB_HOST"), os.Getenv("DB_USER"), os.Getenv("DB_NAME"), os.Getenv("DB_MODE"), os.Getenv("DB_PASS"),
  33. ))
  34. if err != nil {
  35. log.Fatal(err)
  36. }
  37. return &Session{DB: db}
  38. }
  39. }
  40.  
  41. func logFatalIfError(err error) {
  42. if err != nil {
  43. log.Fatal(err)
  44. }
  45. }
Add Comment
Please, Sign In to add comment