-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchat.go
More file actions
61 lines (53 loc) · 1.07 KB
/
chat.go
File metadata and controls
61 lines (53 loc) · 1.07 KB
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
package main
import (
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
"github.com/gorilla/websocket"
)
type ChatService struct {
store Store
}
func NewChatService(s *Store) *ChatService {
return &ChatService{
store: *s,
}
}
func (s *ChatService) RegisterRouters(r *mux.Router) {
r.HandleFunc("/chat/{id}", s.handleWebSocket)
}
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true
},
}
var roomMap map[string]*room
func (s *ChatService) handleWebSocket(w http.ResponseWriter, r *http.Request) {
roomId := mux.Vars(r)["id"] // Gets params
fmt.Println(roomId)
var room *room
var ok bool
room, ok = roomMap[roomId]
if !ok {
room = newRoom()
roomMap[roomId] = room
go room.run()
}
socket, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Fatal("ServeHTTP:", err)
return
}
client := &client{
socket: socket,
receive: make(chan []byte, 256),
room: room,
}
room.join <- client
defer func() { room.leave <- client }()
go client.write()
client.read()
}