Skip to content

Commit d3eb1f5

Browse files
author
Lapp
committed
handler: refactored code, rm root handler. hub, main, connection: refactored code
1 parent 8712af0 commit d3eb1f5

File tree

4 files changed

+7
-13
lines changed

4 files changed

+7
-13
lines changed

connection.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ type connection struct {
88
hub *hub
99
}
1010

11-
func newConnection(ws *websocket.Conn, hub *hub) connection {
12-
return connection{
11+
func newConnection(ws *websocket.Conn, hub *hub) *connection {
12+
return &connection{
1313
ws: ws,
1414
send: make(chan []byte, 256),
1515
hub: hub,

handler.go

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package main
22

33
import (
4-
"fmt"
54
"github.com/gorilla/websocket"
65
"net/http"
76
)
@@ -20,24 +19,19 @@ func newHandler(hub *hub) *handler {
2019
}
2120

2221
func (h *handler) initRoutes() {
23-
http.HandleFunc("/", h.index)
2422
http.HandleFunc("/chat", h.chat)
2523
}
2624

27-
func (h *handler) index(w http.ResponseWriter, r *http.Request) {
28-
fmt.Fprint(w, "<h1>Chat on websockets</h1>")
29-
}
30-
3125
func (h *handler) chat(w http.ResponseWriter, r *http.Request) {
3226
ws, err := upgrader.Upgrade(w, r, nil)
3327
if err != nil {
3428
return
3529
}
3630

3731
conn := newConnection(ws, h.hub)
38-
conn.hub.register <- &conn
32+
conn.hub.register <- conn
3933
defer func() {
40-
conn.hub.unregister <- &conn
34+
conn.hub.unregister <- conn
4135
}()
4236

4337
go conn.write()

hub.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,8 @@ type hub struct {
77
unregister chan *connection
88
}
99

10-
func newHub() hub {
11-
return hub{
10+
func newHub() *hub {
11+
return &hub{
1212
connections: make(map[*connection]struct{}),
1313
broadcast: make(chan []byte),
1414
register: make(chan *connection),

main.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import (
1010

1111
func main() {
1212
hub := newHub()
13-
handler := newHandler(&hub)
13+
handler := newHandler(hub)
1414
handler.initRoutes()
1515
go hub.run()
1616

0 commit comments

Comments
 (0)