Meaningful names for hub

This commit is contained in:
Jean de Klerk 2016-05-18 08:56:16 -06:00
parent 1f512fc3f0
commit a6108176e8
4 changed files with 19 additions and 16 deletions

3
.gitignore vendored
View File

@ -20,3 +20,6 @@ _cgo_export.*
_testmain.go
*.exe
.idea/
*.iml

View File

@ -42,7 +42,7 @@ type connection struct {
// readPump pumps messages from the websocket connection to the hub.
func (c *connection) readPump() {
defer func() {
h.unregister <- c
mainHub.unregister <- c
c.ws.Close()
}()
c.ws.SetReadLimit(maxMessageSize)
@ -56,7 +56,7 @@ func (c *connection) readPump() {
}
break
}
h.broadcast <- message
mainHub.broadcast <- message
}
}
@ -99,7 +99,7 @@ func serveWs(w http.ResponseWriter, r *http.Request) {
return
}
c := &connection{send: make(chan []byte, 256), ws: ws}
h.register <- c
mainHub.register <- c
go c.writePump()
c.readPump()
}

View File

@ -20,30 +20,30 @@ type hub struct {
unregister chan *connection
}
var h = hub{
var mainHub = hub{
broadcast: make(chan []byte),
register: make(chan *connection),
unregister: make(chan *connection),
connections: make(map[*connection]bool),
}
func (h *hub) run() {
func (hub *hub) run() {
for {
select {
case c := <-h.register:
h.connections[c] = true
case c := <-h.unregister:
if _, ok := h.connections[c]; ok {
delete(h.connections, c)
case c := <-hub.register:
hub.connections[c] = true
case c := <-hub.unregister:
if _, ok := hub.connections[c]; ok {
delete(hub.connections, c)
close(c.send)
}
case m := <-h.broadcast:
for c := range h.connections {
case m := <-hub.broadcast:
for c := range hub.connections {
select {
case c.send <- m:
default:
close(c.send)
delete(h.connections, c)
delete(hub.connections, c)
}
}
}

View File

@ -12,7 +12,7 @@ import (
)
var addr = flag.String("addr", ":8080", "http service address")
var homeTempl = template.Must(template.ParseFiles("home.html"))
var homeTemplate = template.Must(template.ParseFiles("home.html"))
func serveHome(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
@ -24,12 +24,12 @@ func serveHome(w http.ResponseWriter, r *http.Request) {
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
homeTempl.Execute(w, r.Host)
homeTemplate.Execute(w, r.Host)
}
func main() {
flag.Parse()
go h.run()
go mainHub.run()
http.HandleFunc("/", serveHome)
http.HandleFunc("/ws", serveWs)
err := http.ListenAndServe(*addr, nil)