Skip to content

Commit 575efa1

Browse files
committed
Fix panic closing closed channel
1 parent 15af2e4 commit 575efa1

File tree

1 file changed

+24
-38
lines changed

1 file changed

+24
-38
lines changed

hub.go

+24-38
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,27 @@ const commands = "{\"Commands\": [" +
5454
"\"hostname\", " +
5555
"\"version\"]} "
5656

57+
func (h *hub) unregisterConnection(c *connection) {
58+
if _, contains := h.connections[c]; !contains {
59+
return
60+
}
61+
delete(h.connections, c)
62+
close(c.send)
63+
}
64+
65+
func (h *hub) sendToRegisteredConnections(data []byte) {
66+
for c := range h.connections {
67+
select {
68+
case c.send <- data:
69+
//log.Print("did broadcast to ")
70+
//log.Print(c.ws.RemoteAddr())
71+
//c.send <- []byte("hello world")
72+
default:
73+
h.unregisterConnection(c)
74+
}
75+
}
76+
}
77+
5778
func (h *hub) run() {
5879
for {
5980
select {
@@ -65,49 +86,14 @@ func (h *hub) run() {
6586
c.send <- []byte("{\"Hostname\" : \"" + *hostname + "\"} ")
6687
c.send <- []byte("{\"OS\" : \"" + runtime.GOOS + "\"} ")
6788
case c := <-h.unregister:
68-
delete(h.connections, c)
69-
// put close in func cuz it was creating panics and want
70-
// to isolate
71-
func() {
72-
// this method can panic if websocket gets disconnected
73-
// from users browser and we see we need to unregister a couple
74-
// of times, i.e. perhaps from incoming data from serial triggering
75-
// an unregister. (NOT 100% sure why seeing c.send be closed twice here)
76-
defer func() {
77-
if e := recover(); e != nil {
78-
log.Println("Got panic: ", e)
79-
}
80-
}()
81-
close(c.send)
82-
}()
89+
h.unregisterConnection(c)
8390
case m := <-h.broadcast:
8491
if len(m) > 0 {
8592
checkCmd(m)
86-
87-
for c := range h.connections {
88-
select {
89-
case c.send <- m:
90-
//log.Print("did broadcast to ")
91-
//log.Print(c.ws.RemoteAddr())
92-
//c.send <- []byte("hello world")
93-
default:
94-
delete(h.connections, c)
95-
close(c.send)
96-
}
97-
}
93+
h.sendToRegisteredConnections(m)
9894
}
9995
case m := <-h.broadcastSys:
100-
for c := range h.connections {
101-
select {
102-
case c.send <- m:
103-
//log.Print("did broadcast to ")
104-
//log.Print(c.ws.RemoteAddr())
105-
//c.send <- []byte("hello world")
106-
default:
107-
delete(h.connections, c)
108-
close(c.send)
109-
}
110-
}
96+
h.sendToRegisteredConnections(m)
11197
}
11298
}
11399
}

0 commit comments

Comments
 (0)