forked from tada-team/nane
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
100 lines (84 loc) · 2.04 KB
/
server.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
package main
import (
"encoding/json"
"io"
"log"
"net/http"
"strings"
"github.com/gorilla/websocket"
"github.com/tada-team/nane/nane"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool { return true }, // XXX
}
func broadcast(v *nane.Message) {
for conn := range sessions {
if err := conn.WriteJSON(v); err != nil {
log.Println("write json fail:", err)
}
}
}
func wsHandler(w http.ResponseWriter, r *http.Request) error {
username := strings.TrimSpace(r.URL.Query().Get("username"))
if username == "" {
username = strings.TrimSpace(r.URL.Query().Get("name")) // backward compatibility
}
if username == "" {
w.WriteHeader(http.StatusUnauthorized)
_, _ = io.WriteString(w, "name required")
return nil
}
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
w.WriteHeader(http.StatusUpgradeRequired)
_, _ = io.WriteString(w, "upgrade failed")
return nil
}
session := Session{conn: conn}
session.Username = username
sessions[conn] = session
log.Println("+connection:", len(sessions))
defer func() {
delete(sessions, conn)
log.Println("-connection:", len(sessions))
}()
for {
messageType, msg, err := conn.ReadMessage()
if err != nil {
return err
}
switch messageType {
case websocket.CloseMessage:
return nil
case websocket.TextMessage, websocket.BinaryMessage:
ping := new(nane.Ping)
if err := json.Unmarshal(msg, &ping); err != nil {
return err
}
if ping.Ping {
log.Println("got ping from", username)
if err := conn.WriteJSON(nane.Pong{Pong: true}); err != nil {
return err
}
continue
}
message := new(nane.Message)
if err := json.Unmarshal(msg, &message); err != nil {
return err
}
log.Println("got message", strings.TrimSpace(string(msg)))
if err := addMessage(session.Sender, message); err != nil {
_, ok := err.(contentError)
if ok {
log.Println("warn:", err)
continue
}
return err
}
broadcast(message)
message.Id = ""
}
}
}