-
Notifications
You must be signed in to change notification settings - Fork 2
/
user_websocket.go
68 lines (57 loc) · 1.3 KB
/
user_websocket.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
package chat
import (
"encoding/json"
"errors"
"net/http"
"github.com/gorilla/websocket"
)
var errNameNotAvailable = errors.New("That name is not available")
// A wsUser represents a client connected via a websocket.
type wsUser struct {
currentRoomName string
muted map[string]bool
username string
conn *websocket.Conn
send chan<- *message
}
func newWsUser(w http.ResponseWriter, r *http.Request, h *hub) (*wsUser, error) {
user := &struct {
Name string
}{}
err := json.NewDecoder(r.Body).Decode(&user)
if err != nil {
return nil, err
}
defer r.Body.Close()
if _, ok := h.users[user.Name]; ok {
return nil, errNameNotAvailable
}
wsconn, err := websocket.Upgrade(w, r, nil, 1024, 1024)
if err != nil {
return nil, err
}
return &wsUser{
currentRoomName: defaultChannelName,
muted: make(map[string]bool),
username: user.Name,
conn: wsconn,
send: h.messageCh,
}, nil
}
func (ws *wsUser) read() error {
for {
msg := &message{}
err := ws.conn.ReadJSON(msg)
if err != nil {
// not sure how to handle this based on severity...
continue
}
ws.send <- msg
}
}
func (ws *wsUser) write(message *message) error {
return ws.conn.WriteJSON(message)
}
func (ws *wsUser) close() {
ws.conn.Close()
}