-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
96 lines (78 loc) · 1.91 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
package main
import (
"context"
"gateway/handlers"
"gateway/services"
"log"
"net/http"
"os"
"os/signal"
"sync"
"syscall"
"time"
)
func main() {
pool := handlers.NewPool()
ctx, cancel := context.WithCancel(context.Background())
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
handlers.StartTCPServer(ctx, pool)
}()
wg.Add(1)
go func() {
defer wg.Done()
handlers.HandlePool(ctx, pool)
}()
wg.Add(1)
go func() {
defer wg.Done()
services.CleanupOldEntries(ctx)
}()
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
handlers.HandleWebSocket(pool, w, r)
})
apiGateway := &http.Server{
Addr: ":8081",
Handler: http.HandlerFunc(handlers.HandleAPI),
}
wg.Add(1)
go func() {
defer wg.Done()
log.Println("API Gateway started on port 8081")
if err := apiGateway.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("API Gateway server failed: %v", err)
}
}()
wsServer := &http.Server{
Addr: ":8080",
Handler: nil,
}
wg.Add(1)
go func() {
defer wg.Done()
if err := wsServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("WebSocket server failed: %v", err)
}
}()
log.Println("WebSocket Server started on port 8080")
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
<-stop
log.Println("Shutting down server...")
// Initiate graceful shutdown
cancel()
// Shutdown the HTTP server with a timeout
ctxShutDown, cancelShutDown := context.WithTimeout(context.Background(), 5*time.Second)
defer cancelShutDown()
if err := wsServer.Shutdown(ctxShutDown); err != nil {
log.Fatalf("WebSocket Server Shutdown Failed:%+v", err)
}
if err := apiGateway.Shutdown(ctxShutDown); err != nil {
log.Fatalf("API Gateway Server Shutdown Failed:%+v", err)
}
// Wait for all goroutines to finish
wg.Wait()
log.Println("Server gracefully stopped")
}