-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
110 lines (93 loc) · 2.49 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
101
102
103
104
105
106
107
108
109
110
package main
import (
"encoding/json"
"errors"
"fmt"
"log/slog"
"os"
"time"
"alfredoramos.mx/csp-reporter/app"
"alfredoramos.mx/csp-reporter/routes"
"alfredoramos.mx/csp-reporter/tasks"
"alfredoramos.mx/csp-reporter/utils"
"github.com/getsentry/sentry-go"
"github.com/gofiber/fiber/v2"
"github.com/joho/godotenv"
)
func main() {
// Set default timezone
time.Local = utils.DefaultLocation()
// Sentry
app.SetupSentry()
defer sentry.Flush(3 * time.Second)
// Load environment variables
if err := godotenv.Load(); err != nil {
sentry.CaptureException(err)
slog.Error(fmt.Sprintf("Could not load .env file: %v", err))
os.Exit(1)
}
// Application initialization
app.SetupDefaultData()
defer func() {
db, err := app.DB().DB()
if err != nil {
sentry.CaptureException(err)
slog.Error(fmt.Sprintf("Could not get database interface: %v", err))
}
if err := db.Close(); err != nil {
sentry.CaptureException(err)
slog.Error(fmt.Sprintf("Error closing database connection: %v", err))
}
}()
// Setup app
app := fiber.New(fiber.Config{
StrictRouting: true,
ErrorHandler: func(c *fiber.Ctx, err error) error {
sentry.CaptureException(err)
slog.Error(fmt.Sprintf("Application error handler: %v", err))
code := fiber.StatusInternalServerError
msg := "The server has encountered an error that cannot be handled."
var e *fiber.Error
if errors.As(err, &e) {
code = e.Code
msg = e.Message
}
return c.Status(code).JSON(&fiber.Map{"error": []string{msg}})
},
AppName: os.Getenv("APP_NAME"),
JSONEncoder: json.Marshal,
JSONDecoder: json.Unmarshal,
})
// Setup routes
routes.SetupRoutes(app)
// Asynq server
go func() {
queue := tasks.AsynqServer()
mux := tasks.AsynqServeMux()
if err := queue.Run(mux); err != nil {
sentry.CaptureException(err)
slog.Error(fmt.Sprintf("Could not run queue server: %v", err))
os.Exit(1)
}
}()
defer func() {
if err := tasks.AsynqClient().Close(); err != nil {
sentry.CaptureException(err)
slog.Error(fmt.Sprintf("Could not close Asynq client: %v", err))
}
}()
// Periodic tasks
go func() {
manager := tasks.AsynqPeriodicTaskManager()
if err := manager.Run(); err != nil {
sentry.CaptureException(err)
slog.Error(fmt.Sprintf("Could not run periodic tasks manager: %v", err))
}
}()
// Setup server
if err := app.Listen(os.Getenv("APP_ADDRESS")); err != nil {
sentry.CaptureException(err)
slog.Error(fmt.Sprintf("Could not setup server: %v", err))
os.Exit(1)
}
}