-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
99 lines (74 loc) · 2.11 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
package main
import (
"log"
"net/http"
"strconv"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true
},
}
var clientsMap = make(map[int]*websocket.Conn)
// UnComment it for Local Devlopment
// func init() {
// err := godotenv.Load(".env")
// if err != nil {
// log.Fatal("Error loading .env file")
// }
// }
func main() {
initDatabase()
router := gin.Default()
// Apply custom CORS middleware (allowing all origins)
router.Use(cors.New(cors.Config{
AllowOrigins: []string{"*"},
AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowHeaders: []string{"Authorization", "Content-Type"}, // Allow Authorization header
ExposeHeaders: []string{"Content-Length"},
AllowCredentials: true,
}))
router.POST("/signIn", signIn)
router.POST("/signUp", signUp)
protected := router.Group("/")
protected.Use(JWTMiddleware())
protected.GET("/getAllUsers", getAllUser)
protected.GET("/getChatHistory", getChatHistory)
protected.GET("/getOnlineUsers", getOnlineUser)
// Serve React static files (wildcard path should be last)
router.Static("/assets", "./client/dist/assets")
router.NoRoute(func(c *gin.Context) {
c.File("./client/dist/index.html")
})
router.GET("/ws", handleWebSocket)
if err := router.Run(":8080"); err != nil {
log.Fatal("Server failed to start:", err)
}
}
func handleWebSocket(c *gin.Context) {
// Upgrade HTTP request to WebSocket
websocket, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
log.Println("Error upgrading to WebSocket:", err)
return
}
defer websocket.Close()
// Extract id from query parameters
userId, err := strconv.Atoi(c.Query("userId"))
if err != nil {
log.Println("Socket UserId not provided")
websocket.Close()
return
}
clientsMap[userId] = websocket
log.Printf("WebSocket connected: %d", userId)
// Listen for messages
listen(websocket)
delete(clientsMap, userId)
log.Printf("WebSocket disconnected: %d", userId)
}