"github.com/gorilla/websocket"
// Time allowed to write a message to the peer.
writeWait
=
10
*
time
.
Second
// Time allowed to read the next pong message from the peer.
pongWait
=
60
*
time
.
Second
// Send pings to peer with this period. Must be less than pongWait.
pingPeriod
=
(
pongWait
*
9
)
/
10
// Maximum message size allowed from peer.
newline
=
[]
byte
{
'\n'
}
var
upgrader
=
websocket.
Upgrader
{
// Client is a middleman between the websocket connection and the hub.
// The websocket connection.
// Buffered channel of outbound messages.
// readPump pumps messages from the websocket connection to the hub.
// The application runs readPump in a per-connection goroutine. The application
// ensures that there is at most one reader on a connection by executing all
// reads from this goroutine.
func
(
c
*
Client
)
readPump
() {
c
.
hub
.
unregister
<-
c
c
.
conn
.
SetReadLimit
(
maxMessageSize
)
c
.
conn
.
SetReadDeadline
(
time
.
Now
().
Add
(
pongWait
))
c
.
conn
.
SetPongHandler
(
func
(
string
)
error
{
c
.
conn
.
SetReadDeadline
(
time
.
Now
().
Add
(
pongWait
));
return
nil
})
_
,
message
,
err
:=
c
.
conn
.
ReadMessage
()
if
websocket
.
IsUnexpectedCloseError
(
err
,
websocket
.
CloseGoingAway
,
websocket
.
CloseAbnormalClosure
) {
log
.
Printf
(
"error: %v"
,
err
)
message
=
bytes
.
TrimSpace
(
bytes
.
Replace
(
message
,
newline
,
space
,
-
1
))
c
.
hub
.
broadcast
<-
message
// writePump pumps messages from the hub to the websocket connection.
// A goroutine running writePump is started for each connection. The
// application ensures that there is at most one writer to a connection by
// executing all writes from this goroutine.
func
(
c
*
Client
)
writePump
() {
ticker
:=
time
.
NewTicker
(
pingPeriod
)
case
message
,
ok
:=
<-
c
.
send
:
c
.
conn
.
SetWriteDeadline
(
time
.
Now
().
Add
(
writeWait
))
// The hub closed the channel.
c
.
conn
.
WriteMessage
(
websocket
.
CloseMessage
, []
byte
{})
w
,
err
:=
c
.
conn
.
NextWriter
(
websocket
.
TextMessage
)
// Add queued chat messages to the current websocket message.
for
i
:=
0
;
i
<
n
;
i
++
{
w
.
Write
(
<-
c
.
send
)
if
err
:=
w
.
Close
();
err
!=
nil
{
c
.
conn
.
SetWriteDeadline
(
time
.
Now
().
Add
(
writeWait
))
if
err
:=
c
.
conn
.
WriteMessage
(
websocket
.
PingMessage
,
nil
);
err
!=
nil
{
// serveWs handles websocket requests from the peer.
func
serveWs
(
hub
*
Hub
,
w
http.
ResponseWriter
,
r
*
http.
Request
) {
conn
,
err
:=
upgrader
.
Upgrade
(
w
,
r
,
nil
)
client
:=
&
Client
{
hub
:
hub
,
conn
:
conn
,
send
:
make
(
chan
[]
byte
,
256
)}
client
.
hub
.
register
<-
client
// Allow collection of memory referenced by the caller by doing all work in