Created
January 8, 2018 06:42
-
-
Save jasonmccallister/f282d4d1265f93bfc44aae98bcda0e13 to your computer and use it in GitHub Desktop.
entity pattern
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 entity | |
import ( | |
"fmt" | |
"log" | |
"os" | |
"github.com/jinzhu/gorm" | |
_ "github.com/jinzhu/gorm/dialects/postgres" | |
_ "github.com/jinzhu/gorm/dialects/sqlite" | |
) | |
// 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. | |
// Creating a new entity is as easy as | |
type Session struct { | |
DB *gorm.DB | |
} | |
// NewSession uses envrionment variables to create a new services to connect to a GORM database. | |
// if the APP_ENV is set to testing, an in-memory database (sqlite) will be used for easy testing. | |
func NewSession() *Session { | |
switch os.Getenv("APP_ENV") { | |
case "testing": | |
db, err := gorm.Open("sqlite", ":memory") | |
if err != nil { | |
log.Fatal(err) | |
} | |
return &Session{DB: db} | |
default: | |
db, err := gorm.Open("postgres", fmt.Sprintf( | |
"host=%v user=%v dbname=%v sslmode=%v password=%v", | |
os.Getenv("DB_HOST"), os.Getenv("DB_USER"), os.Getenv("DB_NAME"), os.Getenv("DB_MODE"), os.Getenv("DB_PASS"), | |
)) | |
if err != nil { | |
log.Fatal(err) | |
} | |
return &Session{DB: db} | |
} | |
} | |
func logFatalIfError(err error) { | |
if err != nil { | |
log.Fatal(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment