Skip to content

Instantly share code, notes, and snippets.

@jasonmccallister
Created January 8, 2018 06:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasonmccallister/f282d4d1265f93bfc44aae98bcda0e13 to your computer and use it in GitHub Desktop.
Save jasonmccallister/f282d4d1265f93bfc44aae98bcda0e13 to your computer and use it in GitHub Desktop.
entity pattern
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