/
chat.go
112 lines (94 loc) · 2.15 KB
/
chat.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
package main
import (
"flag"
"http"
"log"
"template"
"websocket"
"json"
)
var addr = flag.String("addr", ":8080", "http service address")
func main() {
flag.Parse()
go hub()
http.HandleFunc("/", homeHandler)
http.HandleFunc("/ws", webSocketProtocolSwitch)
if err := http.ListenAndServe(*addr, nil); err != nil {
log.Fatal("ListenAndServe:", err)
}
}
func webSocketProtocolSwitch(c http.ResponseWriter, req *http.Request) {
// Handle old and new versions of protocol.
if _, found := req.Header["Sec-Websocket-Key1"]; found {
websocket.Handler(clientHandler).ServeHTTP(c, req)
} else {
websocket.Draft75Handler(clientHandler).ServeHTTP(c, req)
}
}
type message struct {
Text string
Id int
User string
Command string
}
var messageChan = make(chan message)
type subscription struct {
conn *websocket.Conn
subscribe bool
}
var subscriptionChan = make(chan subscription)
func hub() {
conns := make(map[*websocket.Conn]int)
for {
select {
case subscription := <-subscriptionChan:
conns[subscription.conn] = 0, subscription.subscribe
case message := <-messageChan:
for conn, _ := range conns {
j, err := json.Marshal(message)
if err != nil {
log.Print(err)
conn.Close()
}
if _, err := conn.Write(j); err != nil {
log.Print(err)
conn.Close()
}
}
}
}
}
func clientHandler(ws *websocket.Conn) {
defer func() {
subscriptionChan <- subscription{ws, false}
ws.Close()
}()
subscriptionChan <- subscription{ws, true}
for {
buf := make([]byte, 128)
n, err := ws.Read(buf)
if err != nil {
log.Print("Reading Buffer: ", err)
break
}
var m message
err = json.Unmarshal(buf[0:n], &m)
if err != nil {
log.Print("Parsing JSON: ", buf, m, err)
break
}
messageChan <- message{m.Text, m.Id, m.User, m.Command}
}
}
// Handle home page requests.
func homeHandler(c http.ResponseWriter, req *http.Request) {
homeTempl.Execute(c, req.Host)
}
var homeTempl *template.Template
func init() {
homeTempl = template.New(nil)
homeTempl.SetDelims("<<", ">>")
if err := homeTempl.ParseFile("index.html"); err != nil {
panic("template error: " + err.String())
}
}