-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.go
More file actions
75 lines (64 loc) · 1.58 KB
/
Copy pathapp.go
File metadata and controls
75 lines (64 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package helios
import (
"net/http"
"os"
"github.com/gorilla/sessions"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite" // use sqlite dialect
)
// Helios is the core of the apps
type Helios struct {
models []interface{}
store *sessions.CookieStore
}
// App will be the core app that has all the models
// and be the core of the server
var App Helios
// DB is pointer to gorm.DB that can be used
// directly for ORM and database
var DB *gorm.DB
// Initialize the database to production database
func (app *Helios) Initialize() error {
var err error
DB, err = gorm.Open("sqlite3", "db.sqlite3")
if err != nil {
return err
}
key := []byte(os.Getenv("HELIOS_SECRET"))
app.store = sessions.NewCookieStore(key)
return nil
}
// RegisterModel so the database will be migrated
func (app *Helios) RegisterModel(model interface{}) {
app.models = append(app.models, model)
}
// CloseDB close the database connection
func (app *Helios) CloseDB() {
DB.Close()
}
// Migrate migrate all the models
func (app *Helios) Migrate() {
for _, model := range app.models {
DB.AutoMigrate(model)
}
}
// BeforeTest has to be called everytime a test is run
// It will reset the database
func (app *Helios) BeforeTest() {
if DB == nil {
var err error
DB, err = gorm.Open("sqlite3", ":memory:")
if err != nil {
panic(err)
}
app.Migrate()
} else {
for _, model := range app.models {
DB.Unscoped().Delete(model, "true")
}
}
}
func (app *Helios) getSession(r *http.Request) *sessions.Session {
session, _ := app.store.Get(r, os.Getenv("SESSION_NAME"))
return session
}