-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkernel.go
165 lines (132 loc) · 3.5 KB
/
kernel.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
package main
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/logger"
fiberRecover "github.com/gofiber/fiber/v2/middleware/recover"
"github.com/gofiber/fiber/v2/middleware/requestid"
"log"
"os"
"path"
"rent-n-go-backend/query"
"rent-n-go-backend/utils"
"runtime"
"time"
)
/*
Create a log directory and its file if not exist, then return
the file instance.
*/
func getLogFile() *os.File {
currentDir, _ := utils.GetCurrentDir()
fileDir := path.Join(currentDir, "logs")
err := os.MkdirAll(fileDir, 0700)
if err != nil {
utils.ShouldPanic(err)
}
file, err := os.OpenFile(path.Join(fileDir, "log.txt"), os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
utils.ShouldPanic(err)
}
return file
}
/*
*
Return the corresponding Logger Output based on Application Environment
Return file if in production, return stdOut otherwise.
*/
func getLogOutput() *os.File {
if utils.IsProduction() {
return getLogFile()
}
return os.Stdout
}
/*
Register all application globals middleware.
return file instance to be deferred by server entry point.
Initiated at beginning of routing.
*/
func registerGlobalMiddlewares(app *fiber.App) *os.File {
// Load encryptCookie middleware
//app.Use(encryptcookie.New(encryptcookie.Config{
// Key: viper.GetString("APP_KEY"),
//}))
// Load requestId middleware
app.Use(requestid.New())
file := getLogOutput()
// Load logger middleware
app.Use(logger.New(logger.Config{
Format: "[${ip}]:${port} ${status}:${method} -> ${path} ::${locals:requestid} \n",
Output: file,
}))
// Only if in production, then recover the app.
if utils.IsProduction() {
app.Use(fiberRecover.New())
}
return file
}
// RegisterViewFunc Register custom view utilities
func RegisterViewFunc() map[string]interface{} {
return map[string]interface{}{
"when": func(firstCond any, value any, fallback any) any {
if firstCond != nil {
return value
}
return fallback
},
"inc": func(a int) int {
return a + 1
},
"dec": func(a int) int {
return a - 1
},
"estimate": func(startDate time.Time, endDate time.Time) int {
startDate = time.Date(startDate.Year(), startDate.Month(), startDate.Day(), 0, 0, 0, 0, startDate.Location())
endDate = time.Date(endDate.Year(), endDate.Month(), endDate.Day(), 0, 0, 0, 0, endDate.Location())
diff := endDate.Sub(startDate)
return int(diff.Hours() / 24)
},
}
}
// beforeHook bootstrap any process before begin serving.
func beforeHook(app *fiber.App) *os.File {
// Log some welcome message
log.Println("Welcome to Rent-N-Go Backend!")
log.Println("Running in:", runtime.Version(), "Using:", runtime.GOOS)
if utils.IsProduction() {
log.Println("App is running in production mode.")
}
// Satisfy database connection
utils.SatisfiesDbConnection()
// set default db for query
query.SetDefault(utils.GetDb())
// register the global middleware
file := registerGlobalMiddlewares(app)
// get argument of app
args := os.Args[1:]
processMigration(args)
utils.Session.InitStore()
return file
}
/*
*
An global middleware that initiated at the end of routing.
*/
func afterHook(app *fiber.App) {
// set up 404 handler
app.Use(func(c *fiber.Ctx) error {
statusCode := fiber.StatusNotFound
message := "Ups, can't find that!"
c.Status(statusCode)
if utils.WantsJson(c) {
return c.JSON(fiber.Map{
"app": utils.GetApp(),
"message": message,
"status": statusCode,
})
}
return c.Render("error", fiber.Map{
"Code": statusCode,
"Message": message,
})
})
}