/
manchester.go
69 lines (53 loc) · 1.81 KB
/
manchester.go
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
package manchester
import (
"github.com/gin-gonic/gin"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite" // initializes SQLite GORM dialect
log "github.com/sirupsen/logrus"
_ "github.com/surmus/tire-change-workshop/api/manchester" // docs is generated by Swag CLI, you have to import it.
"github.com/surmus/tire-change-workshop/internal/shared"
"gopkg.in/gormigrate.v1"
"time"
)
var db *gorm.DB
// Init initializes manchester application context by setting up database and registering REST endpoints,
// returns Gin Router instance with registered endpoints
func Init(debugMode bool) *gin.Engine {
db = initDB(debugMode)
repository := newTireChangeTimeRepository(db)
service := newTireChangeTimesService(repository)
if !debugMode {
gin.SetMode(gin.ReleaseMode)
}
r := gin.New()
// Add a ginrus middleware, which:
// - Logs all requests, like a combined access and errors log.
// - Logs to stdout.
// - RFC3339 with UTC time format.
r.Use(shared.GinRusMiddleware(log.StandardLogger(), time.RFC3339, true))
// Recovery middleware recovers from any panics and writes a 500 if there was one.
r.Use(gin.Recovery())
// ErrorHandler middleware catches application errors and renders them as XML
r.Use(errorHandlerMiddleware())
// Register application routes
registerController(r, service)
return r
}
func initDB(debugMode bool) *gorm.DB {
db, err := gorm.Open("sqlite3", ":memory:")
if err != nil {
panic(err)
}
db.LogMode(debugMode)
runDBMigration(db)
log.Info("Database initialized")
return db
}
func runDBMigration(db *gorm.DB) {
log.Info("DB migrations :: START")
m := gormigrate.New(db, gormigrate.DefaultOptions, []*gormigrate.Migration{initial})
if err := m.Migrate(); err != nil {
log.Fatalf("Could not migrate: %v", err)
}
log.Info("DB migrations :: COMPLETE")
}