Go gorilla websocket write deadline


I am unable to understand this part of the code which uses c.conn.SetWriteDeadline function.

    // 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

// 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)
    defer func() {
    for {
        select {
        case message, ok := <-c.send:
        case <-ticker.C: 
            c.conn.SetWriteDeadline(time.Now().Add(writeWait)) // 👈 ??
            if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {

I am unable to wrap my head around the ticket channel logic. What are we trying to achieve here?

I am referring to the official docks for go/gorilla/websocket here


From the SetWriteDeadline function documentation:

SetWriteDeadline sets the write deadline on the underlying network connection. 
After a write has timed out, the websocket state is corrupt and
all future writes will return an error. 
A zero value for t means writes will not time out.

So every ticker on the goroutine it is setting the write deadline to the current time plus whatever you have the writeWait const set to. The subsequent line then sends a ping message, with that deadline. This all happens on the ticker interval which is the const pingPeriod. The other go-routine, readPump(), should be setting a read deadline and handler for the pong message. This constant ping-pong keeps the connection alive according to the wait times you have set.

Answered By – sudoshu

Answer Checked By – Marilyn (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.