-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
212 lines (176 loc) · 4.69 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
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
208
209
210
211
212
package main
import (
"context"
"encoding/json"
"log"
"net/http"
"os"
"strings"
"time"
"github.com/google/uuid"
"nhooyr.io/websocket"
)
type Client struct {
ID string `json:"id"`
Nickname string `json:"nickname"`
Color string `json:"color"`
connection *websocket.Conn
context context.Context
roomName string
}
const (
// Message types
MESSAGE = "message"
NOTIFICATION = "notification"
)
type Message struct {
Type string `json:"type"` // message or notification
From Client `json:"from"`
to string
Content string `json:"content"` // required in Type: message
IsTyping bool `json:"isTyping"` // required in Type: notification
SentAt string `json:"sentAt"`
}
var (
clients map[*Client]bool = make(map[*Client]bool)
joinCh chan *Client = make(chan *Client)
broadcastCh chan Message = make(chan Message)
)
func wsHandler(w http.ResponseWriter, r *http.Request) {
nickname := r.URL.Query().Get("nickname")
room := r.URL.Query().Get("room")
// validate nickname
if nickname == "" {
log.Fatal("Server: No nickname provided")
}
// validate room
if room == "" {
log.Println("SERVER: No room provided, using default room")
room = "general"
}
// open connection
conn, err := websocket.Accept(w, r, &websocket.AcceptOptions{
InsecureSkipVerify: true, // disable CORS
})
if err != nil {
log.Fatal("Server: Failed to open connection:", err)
}
go broadcast()
go joiner()
// create a client
client := Client{
ID: uuid.New().String(),
Nickname: nickname,
connection: conn,
context: r.Context(),
roomName: room,
}
joinCh <- &client
reader(&client, room)
}
func reader(client *Client, room string) {
for {
_, data, err := client.connection.Read(client.context)
// notifies when client disconnected
if err != nil {
log.Println("SERVER: " + client.Nickname + " disconnected from room " + client.roomName)
broadcastCh <- Message{
Type: NOTIFICATION,
From: Client{Nickname: client.Nickname},
to: room,
IsTyping: false,
SentAt: getTimestamp(),
}
delete(clients, client)
client.connection.Close(websocket.StatusNormalClosure, "")
broadcastCh <- Message{
Type: MESSAGE,
From: Client{Nickname: "SERVER", Color: "#64BFFF"},
to: room,
Content: client.Nickname + " disconnected",
SentAt: getTimestamp(),
}
break
}
// deserialize message
var msgReceived Message
json.Unmarshal(data, &msgReceived)
// log message to server
if strings.ToLower(msgReceived.Type) == MESSAGE {
log.Printf("ROOM: %s -> %s: %s\n", room, msgReceived.From.Nickname, msgReceived.Content)
} else if msgReceived.Type == NOTIFICATION {
log.Printf("ROOM: %s -> %s is typing: %t\n", room, msgReceived.From.Nickname, msgReceived.IsTyping)
} else {
log.Printf("ROOM: %s -> %s sent an unknown message type\n", room, msgReceived.From.Nickname)
}
if client.Color == "" && msgReceived.From.Color != "" {
client.Color = msgReceived.From.Color
}
// broadcast message to all clients
broadcastCh <- Message{
Type: msgReceived.Type,
From: Client{
ID: client.ID,
Nickname: client.Nickname,
Color: client.Color,
},
to: room,
Content: msgReceived.Content,
IsTyping: msgReceived.IsTyping,
SentAt: getTimestamp(),
}
}
}
func joiner() {
// loop while channel is open
for client := range joinCh {
clients[client] = true
log.Println("SERVER: " + client.Nickname + " connected in room " + client.roomName)
// notifies when a new client connects
broadcastCh <- Message{
Type: MESSAGE,
From: Client{Nickname: "SERVER", Color: "#64BFFF"},
to: client.roomName,
Content: client.Nickname + " connected",
SentAt: getTimestamp(),
}
}
}
func broadcast() {
for msg := range broadcastCh {
for client := range clients {
if client.roomName == msg.to {
message, _ := json.Marshal(msg)
client.connection.Write(
client.context,
websocket.MessageText,
message,
)
}
}
}
}
func clientsHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
var res []*Client
roomFromQuery := r.URL.Query().Get("room")
for c := range clients {
if c.roomName == roomFromQuery {
res = append(res, c)
}
}
json.NewEncoder(w).Encode(res)
}
func getTimestamp() string {
return time.Now().UTC().Add(time.Duration(-3) * time.Hour).Format("02-01-2006 15:04:05")
}
func main() {
http.Handle("/", http.FileServer(http.Dir("./public")))
http.HandleFunc("/ws", wsHandler)
http.HandleFunc("/clients", clientsHandler)
port := os.Getenv("PORT")
if port == "" {
port = "3000"
}
http.ListenAndServe("0.0.0.0:"+port, nil)
}