@@ -39,11 +39,47 @@ func (connection *connection) handleFrame(ctx context.Context) error {
39
39
return nil
40
40
}
41
41
42
+ type connections struct {
43
+ data map [* connection ]bool
44
+ mutex sync.Mutex
45
+ }
46
+
47
+ func newConnections () connections {
48
+ return connections {data : make (map [* connection ]bool )}
49
+ }
50
+
51
+ func (connections * connections ) store (key * connection , value bool ) {
52
+ connections .mutex .Lock ()
53
+ connections .data [key ] = value
54
+ connections .mutex .Unlock ()
55
+ }
56
+
57
+ func (connections * connections ) delete (key * connection ) {
58
+ connections .mutex .Lock ()
59
+ delete (connections .data , key )
60
+ connections .mutex .Unlock ()
61
+ }
62
+
63
+ func (connections * connections ) close () {
64
+ connections .mutex .Lock ()
65
+ defer connections .mutex .Unlock ()
66
+
67
+ for connection := range connections .data {
68
+ connection .Close (websocket .StatusNormalClosure , "server shutting down" )
69
+ }
70
+ }
71
+
42
72
type wsHandler struct {
43
- connections sync. Map
73
+ connections connections
44
74
waitGroup sync.WaitGroup
45
75
}
46
76
77
+ func newWsHandler () * wsHandler {
78
+ return & wsHandler {
79
+ connections : newConnections (),
80
+ }
81
+ }
82
+
47
83
func (handler * wsHandler ) handle (writer http.ResponseWriter , request * http.Request ) error {
48
84
defer handler .waitGroup .Done ()
49
85
@@ -56,8 +92,8 @@ func (handler *wsHandler) handle(writer http.ResponseWriter, request *http.Reque
56
92
connection := connection {conn , writer , request }
57
93
defer connection .CloseNow ()
58
94
59
- handler .connections .Store ( connection , true )
60
- defer handler .connections .Delete ( connection )
95
+ handler .connections .store ( & connection , true )
96
+ defer handler .connections .delete ( & connection )
61
97
62
98
log .Printf ("opened a connection with %v" , request .RemoteAddr )
63
99
@@ -98,14 +134,6 @@ func (handler *wsHandler) ServeHTTP(writer http.ResponseWriter, request *http.Re
98
134
}
99
135
100
136
func (handler * wsHandler ) close () {
101
- for key , _ := range handler .connections .Range {
102
- connection , ok := key .(connection )
103
- if ! ok {
104
- return
105
- }
106
-
107
- connection .Close (websocket .StatusNormalClosure , "server shutting down" )
108
- }
109
-
137
+ handler .connections .close ()
110
138
handler .waitGroup .Wait ()
111
139
}
0 commit comments