-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
119 lines (102 loc) · 2.55 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
111
112
113
114
115
116
117
118
119
package main
import (
"encoding/json"
"github.com/gin-gonic/gin"
"github.com/go-redis/redis/v8"
"github.com/gorilla/websocket"
"log"
"net/http"
"sync"
)
type request struct {
Cmd string `json:"cmd"`
ChannelName string `json:"chName"`
Msg string `json:"msg"`
}
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true
},
}
var redisClient *redis.Client
func init() {
redisClient = redis.NewClient(&redis.Options{
Addr: "localhost:6379", // Update with your Redis server address
Password: "", // No password by default
DB: 0, // Default DB
})
}
func handleWebSocket(c *gin.Context) {
userId := c.Query("userId")
if userId == "" {
log.Println("userId is empty")
c.JSON(http.StatusBadRequest, gin.H{"err": "userId not provided"})
return
}
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
log.Println(err)
return
}
log.Println("User " + userId + " connected successfully")
// maintaining list of all subscribed pubsub objects, so once connection is disconnected, we can close all pubsub object
var subscribedChannels = make(map[string]*redis.PubSub)
defer func() {
log.Printf("closing total pubsubs: %d\n", len(subscribedChannels))
for _, ps := range subscribedChannels {
ps.Close()
}
log.Println("closing connection")
conn.Close()
}()
var mutex sync.Mutex
for {
// Read message from the client
_, msg, err := conn.ReadMessage()
if err != nil {
log.Println(err)
return
}
var data request
err = json.Unmarshal(msg, &data)
if err != nil {
continue
}
switch data.Cmd {
case "I-JC": // Join Channel
// if not already subscribed, then only subscribe
if _, ok := subscribedChannels[data.ChannelName]; !ok {
pubsub := redisClient.Subscribe(c, data.ChannelName)
go listenToChannel(conn, pubsub, &mutex)
subscribedChannels[data.ChannelName] = pubsub
}
case "I-SM": // Send Message
err = redisClient.Publish(c, data.ChannelName, userId+": "+data.Msg).Err()
if err != nil {
log.Println(err)
}
}
}
}
// listen for pubsub channel messages in a goroutine
func listenToChannel(conn *websocket.Conn, ps *redis.PubSub, mutex *sync.Mutex) {
for {
msg, ok := <-ps.Channel()
if !ok {
return
}
mutex.Lock()
conn.WriteMessage(websocket.TextMessage, []byte(msg.Payload))
mutex.Unlock()
}
}
func main() {
r := gin.Default()
r.GET("/chat", handleWebSocket)
err := r.Run(":8080")
if err != nil {
log.Fatal(err)
}
}