-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.go
More file actions
207 lines (177 loc) · 6.21 KB
/
main.go
File metadata and controls
207 lines (177 loc) · 6.21 KB
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
package main
import (
"context"
"log"
"net/http"
"os"
"os/signal"
"strconv"
"syscall"
"time"
apiAccomodation "github.com/Infinite-Sum-Games/Am.EventKit/api/accomodation"
apiAnalytics "github.com/Infinite-Sum-Games/Am.EventKit/api/analytics"
apiAttend "github.com/Infinite-Sum-Games/Am.EventKit/api/attendance"
apiAuth "github.com/Infinite-Sum-Games/Am.EventKit/api/auth"
apiBooking "github.com/Infinite-Sum-Games/Am.EventKit/api/booking"
apiDispute "github.com/Infinite-Sum-Games/Am.EventKit/api/dispute"
apiEvent "github.com/Infinite-Sum-Games/Am.EventKit/api/event"
apiOrganizers "github.com/Infinite-Sum-Games/Am.EventKit/api/organizers"
apiPeople "github.com/Infinite-Sum-Games/Am.EventKit/api/people"
apiProfile "github.com/Infinite-Sum-Games/Am.EventKit/api/profile"
apiTag "github.com/Infinite-Sum-Games/Am.EventKit/api/tag"
mq "github.com/Infinite-Sum-Games/Am.EventKit/message-queue"
cmd "github.com/Infinite-Sum-Games/Am.EventKit/cmd"
mail "github.com/Infinite-Sum-Games/Am.EventKit/mail"
mw "github.com/Infinite-Sum-Games/Am.EventKit/middleware"
pkg "github.com/Infinite-Sum-Games/Am.EventKit/pkg"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
)
func SetupRouter(mailerSvc *mail.MailerService) *gin.Engine {
config := cors.Config{
AllowOrigins: []string{cmd.Env.ClientDomain},
AllowWildcard: true,
AllowMethods: []string{"GET", "POST", "DELETE", "PUT", "PATCH", "OPTIONS"},
AllowHeaders: []string{"X-Csrf-Token", "Origin", "Content-Type"},
AllowCredentials: true,
OptionsResponseStatusCode: 204,
MaxAge: 12 * time.Hour,
}
gin.SetMode(gin.ReleaseMode)
r := gin.New()
r.Use(cors.New(config)) // Setup CORS() first before other middlewares
r.Use(mw.MaintainanceMiddleware)
r.Use(pkg.Log.LogMiddleware)
r.Use(pkg.TagRequestWithId)
r.Use(mw.RecoveryPanics)
r.Use(mw.PrometheusMiddleware("anokha-26"))
r.GET("/test", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "Server is live ◪_◪",
})
pkg.Log.SuccessCtx(c)
})
r.GET("/metrics", mw.MetricsHandler())
v1 := r.Group("/api/v1")
authRouter := v1.Group("/auth")
attendanceRouter := v1.Group("/attendance")
userRouter := v1.Group("/user")
eventRouter := v1.Group("/events")
peopleRouter := v1.Group("/people")
tagRouter := v1.Group("/tags")
organizerRouter := v1.Group("/organizers")
analyticsRouter := v1.Group("/analytics")
disputeRouter := v1.Group("/disputes")
accomodationRouter := v1.Group("/accommodation")
apiAuth.StudentAuthRoutes(authRouter)
apiAuth.OrganizerAuthRoutes(authRouter)
apiAuth.AdminAuthRoutes(authRouter)
apiProfile.ProfileRoutes(userRouter)
apiEvent.EventRoutes(eventRouter)
apiTag.TagRoutes(tagRouter)
apiAttend.AttendanceRoutes(attendanceRouter)
apiPeople.PeopleRoutes(peopleRouter)
apiOrganizers.OrganizerRoutes(organizerRouter)
apiOrganizers.OrganizerDashboardRoutes(organizerRouter)
apiBooking.BookingRoutes(eventRouter)
apiAnalytics.AnalyticsRoutes(analyticsRouter)
apiDispute.DisputeRoutes(disputeRouter)
apiAccomodation.AccomodationFormRoutes(accomodationRouter)
apiAccomodation.AccomodationAuthRoutes(accomodationRouter)
apiAccomodation.AccomodationPanelRoutes(accomodationRouter)
apiAccomodation.FinanceRoutes(accomodationRouter)
apiAccomodation.GateRoutes(accomodationRouter)
apiAccomodation.SecurityRoutes(accomodationRouter)
return r
}
func StartApp() {
// Setting up environment variables
config, err := cmd.LoadConfig()
if err != nil {
log.Printf("[CRASH]: Failed to load environment variables: %v", err)
return
}
cmd.Env = config
log.Println("[OK]: Environment variables loaded successfully.")
// Initializing the logger and other middlewares
pkg.Log, err = pkg.InitLogger(cmd.Env.Environment)
if err != nil {
log.Printf("[CRASH]: Logger initialization failed: %v", err)
return
}
pkg.Log.Info("[OK]: Logger initiation successful")
// Initialize RSA
err = cmd.CheckRSAKeyPairExists()
if err != nil {
err = cmd.GenerateRSAKeyPair()
if err != nil {
pkg.Log.Fatal("[CRASH]: Failed to initialize rsa", err)
}
pkg.Log.Info("[OK]: RSA keypair generated and saved successfully.")
} else {
pkg.Log.Info("[OK]: Using existing RSA keypair.")
}
// Setup PASETO
if err := pkg.InitPaseto(); err != nil {
pkg.Log.Fatal("[CRASH]: Paseto initialization failed", err)
}
pkg.Log.Info("[OK]: Paseto initialization successful!")
// Initialize DB Pool
err = cmd.InitDBPool()
if err != nil {
pkg.Log.Fatal("[CRASH]: Failed to initialize database pool", err)
return
}
pkg.Log.Info("[OK]: Initialized database pool successfully")
// Initialize Redis for caching and rate limiing
cmd.Redis, err = cmd.InitRedis()
if err != nil {
pkg.Log.Info("[CRASH]: Redis failed to start")
return
}
pkg.Log.Info("[OK]: Redis serivce started successfully")
// Initialize RabbitMQ for durable message passing
mq.Rabbit, err = mq.NewBroker(cmd.Env.MsgBrokerConnUrl)
if err != nil {
return
}
pkg.Log.Info("[OK]: Message broker initialized successfully.")
// Setup LIVE flags
pkg.InitFlag()
// Initialize Mailer Service
mail.Mail, err = mail.NewMailerService("mail/mail-queue", 4)
if err != nil {
pkg.Log.Fatal("[CRASH]: failed to create mailer service", err)
return
}
mail.Mail.Start()
pkg.Log.Info("[OK]: Mailer service started successfully")
// Initialize server
server := &http.Server{
Addr: ":" + strconv.Itoa(cmd.Env.Port),
Handler: SetupRouter(mail.Mail),
}
go func() {
portStr := strconv.Itoa(cmd.Env.Port)
pkg.Log.Info("[OK]: Start the server on port " + portStr)
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
pkg.Log.Fatal("could not listen on port "+portStr, err)
} // Blocking in nature (?)
}()
// Graceful shutdown with 10 second timeout; no new connections accepted
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
pkg.Log.Info("[OK]: Shutting down server...")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := server.Shutdown(ctx); err != nil {
pkg.Log.Fatal("[OK]: Server forced to shutdown", err)
}
// Mailer shutdown sequence
mail.Mail.Shutdown()
pkg.Log.Info("[OK]: Server shutting down")
}
func main() {
StartApp()
}