github.com/alpe/etcd@v0.1.2-0.20130915230056-09f31af88aeb/web/hub.go (about) 1 package web 2 3 type hub struct { 4 // status 5 open bool 6 7 // Registered connections. 8 connections map[*connection]bool 9 10 // Inbound messages from the connections. 11 broadcast chan string 12 13 // Register requests from the connections. 14 register chan *connection 15 16 // Unregister requests from connections. 17 unregister chan *connection 18 } 19 20 var h = hub{ 21 open: false, 22 broadcast: make(chan string), 23 register: make(chan *connection), 24 unregister: make(chan *connection), 25 connections: make(map[*connection]bool), 26 } 27 28 func Hub() *hub { 29 return &h 30 } 31 32 func HubOpen() bool { 33 return h.open 34 } 35 36 func (h *hub) run() { 37 h.open = true 38 for { 39 select { 40 case c := <-h.register: 41 h.connections[c] = true 42 case c := <-h.unregister: 43 delete(h.connections, c) 44 close(c.send) 45 case m := <-h.broadcast: 46 for c := range h.connections { 47 select { 48 case c.send <- m: 49 default: 50 delete(h.connections, c) 51 close(c.send) 52 go c.ws.Close() 53 } 54 } 55 } 56 } 57 } 58 59 func (h *hub) Send(msg string) { 60 h.broadcast <- msg 61 }