-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
100 lines (80 loc) · 2.16 KB
/
main.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
// main.go
package main
import (
"mailer-api/internal/config"
"mailer-api/internal/constants"
"mailer-api/internal/routes"
"mailer-api/internal/services"
"mailer-api/pkg/database"
"mailer-api/pkg/utils"
"mailer-api/pkg/validator"
"os"
"os/signal"
"syscall"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/compress"
"github.com/gofiber/fiber/v2/middleware/cors"
"github.com/gofiber/fiber/v2/middleware/healthcheck"
"github.com/gofiber/fiber/v2/middleware/helmet"
"github.com/gofiber/fiber/v2/middleware/logger"
"github.com/gofiber/fiber/v2/middleware/requestid"
"github.com/google/uuid"
)
func init() {
// Load all configs
if err := config.LoadConfig(); err != nil {
utils.LogFatal("failed to load configs", err)
}
// Validate environment variables
if err := utils.ValidateConfig(constants.EnvValidationRules); err != nil {
utils.LogFatal("configuration validation failed", err)
}
// Initialize validator
validator.InitValidator()
// Connect to database
if err := database.ConnectDB(); err != nil {
utils.LogFatal("failed to connect to database", err)
}
// Initialize services
services.InitMailService()
}
func setupApp() *fiber.App {
app := fiber.New(fiber.Config{})
// Middleware
app.Use(helmet.New())
app.Use(cors.New())
app.Use(compress.New())
app.Use(healthcheck.New())
app.Use(requestid.New(requestid.Config{
Generator: func() string {
return uuid.New().String()
},
}))
app.Use(logger.New())
return app
}
func main() {
// Setup Fiber app
app := setupApp()
// Setup Redis and Asynq
config.ConnectAsynq()
defer config.AsynqClient.Close()
if err := config.SetupWorkers(config.AsynqServer); err != nil {
utils.LogFatal("failed to setup workers", err)
}
// Setup routes
routes.SetupRoutes(app)
// Graceful shutdown channel
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt, syscall.SIGTERM)
go func() {
<-quit
utils.LogInfo("shutting down server...")
if err := app.Shutdown(); err != nil {
utils.LogFatal("server forced to shutdown", err)
}
config.AsynqServer.Shutdown()
}()
// Start server
utils.LogFatal("failed to start server", app.Listen(":"+utils.GetEnv("PORT")))
}