-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
181 lines (153 loc) · 3.82 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
package main
import (
"encoding/json"
"errors"
"html/template"
"log"
"net/http"
"github.com/gorilla/websocket"
)
type message struct {
Username string `json:"username"`
Text string `json:"text"`
}
type room struct {
ID string
Connections map[*websocket.Conn]bool
Broadcast chan message
Messages []message
}
var rooms = make(map[string]*room)
func handleWebSocket(w http.ResponseWriter, r *http.Request) {
// Upgrade HTTP connection to WebSocket
upgrader := websocket.Upgrader{}
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
// Get room ID from URL query parameter
roomID := r.URL.Query().Get("room")
// Create new room if it doesn't exist
if _, ok := rooms[roomID]; !ok {
rooms[roomID] = &room{
ID: roomID,
Connections: make(map[*websocket.Conn]bool),
Broadcast: make(chan message),
Messages: make([]message, 0),
}
go rooms[roomID].run()
}
// Add connection to room
rooms[roomID].Connections[conn] = true
}
func (r *room) run() {
for {
// Wait for incoming message on broadcast channel
msg := <-r.Broadcast
// Add message to room history
r.Messages = append(r.Messages, msg)
// Broadcast message to all connections in room
for conn := range r.Connections {
err := conn.WriteJSON(msg)
if err != nil {
log.Println(err)
delete(r.Connections, conn)
}
}
}
}
func handleChatMessage(w http.ResponseWriter, r *http.Request) {
// Get room ID from URL query parameter
roomID := r.URL.Query().Get("room")
// Get chat room
chatRoom, ok := rooms[roomID]
if !ok {
http.NotFound(w, r)
return
}
// Parse incoming message from JSON
var msg message
err := json.NewDecoder(r.Body).Decode(&msg)
if err != nil {
log.Println(err)
http.Error(w, "400 Bad request", http.StatusBadRequest)
return
}
// Validate message
err = validateMessage(msg)
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Add message to room history
chatRoom.Messages = append(chatRoom.Messages, msg)
// Broadcast message to all connections in room
chatRoom.Broadcast <- msg
}
func validateMessage(msg message) error {
if msg.Username == "" {
return errors.New("username cannot be empty")
}
if msg.Text == "" {
return errors.New("message cannot be empty")
}
return nil
}
func handleChatRoom(w http.ResponseWriter, r *http.Request) {
// Get room ID from URL query parameter
roomID := r.URL.Query().Get("room")
// Get chat room
chatRoom, ok := rooms[roomID]
if !ok {
http.NotFound(w, r)
return
}
// Define template data
type templateData struct {
RoomID string
Messages []message
}
data := templateData{
RoomID: roomID,
Messages: make([]message, 0),
}
// Collect chat messages
for _, msg := range chatRoom.Messages {
data.Messages = append(data.Messages, msg)
}
// Execute template
tmpl, err := template.ParseFiles("chat.html")
if err != nil {
log.Println(err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
err = tmpl.Execute(w, data)
if err != nil {
log.Println(err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
}
func main() {
// Serve static files
fs := http.FileServer(http.Dir("static"))
http.Handle("/static/", http.StripPrefix("/static/", fs))
// Serve styles.css file
http.HandleFunc("/styles.css", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "static/styles.css")
})
// Register HTTP handlers
http.HandleFunc("/ws", handleWebSocket)
http.HandleFunc("/chat", handleChatRoom)
http.HandleFunc("/message", handleChatMessage)
// Start HTTP server
log.Println("Starting server on :8080")
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal(err)
}
}