generated from zercle/gofiber-skeleton
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
172 lines (143 loc) · 4.78 KB
/
server.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
166
167
168
169
170
171
172
package infrastructure
import (
"fmt"
"log"
"os"
"os/signal"
"syscall"
"time"
"github.com/goccy/go-json"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/cors"
"github.com/gofiber/fiber/v2/middleware/logger"
"github.com/gofiber/fiber/v2/middleware/recover"
"github.com/gofiber/fiber/v2/middleware/session"
"github.com/spf13/viper"
"github.com/thn-lee/01-task-management-api/internal/datasources"
"github.com/thn-lee/01-task-management-api/pkg/logs"
"github.com/thn-lee/01-task-management-api/pkg/models"
"github.com/thn-lee/01-task-management-api/pkg/utils"
)
type Server struct {
models.Resources
Version string
Build string
RunEnv string
PrdMode bool
}
func NewServer(version, buildTag, runEnv string) (server *Server, err error) {
// Init server
server = &Server{
PrdMode: (viper.GetString("app.env") == "production"),
Version: version,
Build: buildTag,
RunEnv: runEnv,
}
// // connect to DB
// mainDbConn, err := datasources.ConnectDb(datasources.DbConfig{
// DbDriver: "sqlite",
// DbName: viper.GetString("db.sqlite.db_name"),
// })
// if err != nil {
// return
// }
// server.RedisStorage, err = connectToRedis()
// if err != nil {
// return
// }
fastHTTPClient := datasources.NewFastHTTPClient(true)
// utils.JsonParserPool = new(fastjson.ParserPool)
// jwtResources, err := NewJwt(viper.GetString("jwt.private"))
// if err != nil {
// return
// }
// init app resources
server.Resources = NewResources(fastHTTPClient, nil, nil, nil, nil)
// something that use resources place here
// pre config server
if err = server.configApp(); err != nil {
return
}
return
}
func (s *Server) Run() (err error) {
app := fiber.New(fiber.Config{
ErrorHandler: customErrorHandler,
ReadTimeout: 60 * time.Second,
ReadBufferSize: 8 * 1024,
Prefork: s.PrdMode,
// speed up json with segmentio/encoding
JSONEncoder: json.Marshal,
JSONDecoder: json.Unmarshal,
// behide reverse proxy
// EnableTrustedProxyCheck: true,
})
// Logger middleware for Fiber that logs HTTP request/response details.
app.Use(logger.New(s.LogConfig))
// Recover middleware for Fiber that recovers from panics anywhere in the stack chain and handles the control to the centralized ErrorHandler.
app.Use(recover.New(recover.Config{EnableStackTrace: !s.PrdMode}))
// CORS middleware for Fiber that that can be used to enable Cross-Origin Resource Sharing with various options.
app.Use(cors.New())
// App Handlers
s.SetupRoutes(app)
// Log GO_ENV
log.Printf("Runtime ENV: %s", viper.GetString("app.env"))
log.Printf("Version: %s", s.Version)
log.Printf("Build: %s", s.Build)
// Listen from a different goroutine
// Listen HTTP
go func() {
if err := app.Listen(":" + viper.GetString("app.port.http")); err != nil {
log.Panic(err)
}
}()
// // Listen HTTPS
// go func() {
// if err := app.ListenTLS(":"+viper.GetString("app.port.https"), viper.GetString("app.path.cert"), viper.GetString("app.path.priv")); err != nil {
// log.Panic(err)
// }
// }()
// Create channel to signify a signal being sent
quit := make(chan os.Signal, 1)
// When an interrupt or termination signal is sent, notify the channel
signal.Notify(quit, os.Interrupt, syscall.SIGTERM)
// This blocks the main thread until an interrupt is received
<-quit
fmt.Println("Gracefully shutting down...")
_ = app.Shutdown()
fmt.Println("Running cleanup tasks...")
// Your cleanup tasks go here
if s.RedisStorage != nil {
s.RedisStorage.Close()
}
fmt.Println("Successful shutdown.")
return
}
func (s *Server) configApp() (err error) {
if s.PrdMode {
s.SessConfig = session.Config{
Expiration: 8 * time.Hour,
KeyLookup: fmt.Sprintf("%s:%s", "cookie", viper.GetString("app.name")),
CookieSecure: true,
CookieHTTPOnly: true,
}
logFileWriter := &logs.LogFileWriter{LogPath: "./log/gofiber-skelton", PrintConsole: true}
s.LogConfig = logger.Config{
Format: "[${blue}${time}${reset}] ${status} - ${ip},${ips} ${method} ${host} ${url}\tUserAgent: ${ua}\tReferer: ${referer}\tAuthorization: ${header:Authorization}\tBytesReceived: ${bytesReceived}\tBytesSent: ${bytesSent}\tError: ${red}${error}${reset}\n",
TimeFormat: "2006-01-02 15:04:05",
Output: logFileWriter,
}
} else {
s.SessConfig = session.ConfigDefault
s.LogConfig = logger.Config{
Format: "[${blue}${time}${reset}] ${status} - ${ip},${ips} ${method} ${host} ${url}\nUserAgent:\t${ua}\nReferer:\t${referer}\nAuthorization:\t${header:Authorization}\nBytesReceived:\t${bytesReceived}\nBytesSent:\t${bytesSent}\nError:\t${red}${error}${reset}\n",
TimeFormat: "2006-01-02 15:04:05",
}
}
// Use redis for session store if available
if s.RedisStorage != nil {
s.SessConfig.Storage = s.RedisStorage
}
utils.SessStore = session.New(s.SessConfig)
return
}