Selaa lähdekoodia

Meaningful names for hub

Jean de Klerk 9 vuotta sitten
vanhempi
commit
a6108176e8
4 muutettua tiedostoa jossa 19 lisäystä ja 16 poistoa
  1. 3 0
      .gitignore
  2. 3 3
      examples/chat/conn.go
  3. 10 10
      examples/chat/hub.go
  4. 3 3
      examples/chat/main.go

+ 3 - 0
.gitignore

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

+ 3 - 3
examples/chat/conn.go

@@ -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()
 }

+ 10 - 10
examples/chat/hub.go

@@ -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)
 				}
 			}
 		}

+ 3 - 3
examples/chat/main.go

@@ -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)