title: WebSocket - Closing Handshake Gorilla
body: <p>Snippet from WebSocket RFC:</p>
  
  <blockquote>
    <p>To <em>Start the WebSocket Closing Handshake</em> with a status code (Section 7.4) /code/ and an optional close reason (Section 7.1.6) /reason/, an endpoint MUST send a Close control frame, as described in Section 5.5.1, whose status code is set to /code/ and whose close reason is set to /reason/.  Once an endpoint has both sent and received a Close control frame, that endpoint SHOULD <em>Close the WebSocket Connection</em> as defined in Section 7.1.1.</p>
  </blockquote>
  
  <p>I am trying to do the Close Handshake using <a href="https://github.com/gorilla/websocket" rel="nofollow">Gorilla WebSocket</a> package with the following code:</p>
  
  <p>Server:</p>
  
  <pre><code>// Create upgrader function
  conn, err := upgrader.Upgrade(w, r, nil)
  
  // If there is an error stop everything.
  if err != nil {
      fmt.Println(err)
      return
  }
  
  for {
      // Read Messages
      _, _, err := conn.ReadMessage()
      // Client is programmed to send a close frame immediately...
      // When reading close frame resend close frame with same
      // reason and code
      conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(1000, "woops"))
      fmt.Println(err)
      break
  }
  </code></pre>
  
  <p>Client:</p>
  
  <pre><code>d := &amp;websocket.Dialer{}
  
  conn, _, err := d.Dial("ws://localhost:8080", nil)
  
  if err != nil {
      fmt.Println(err)
      return
  }
  
  go func() {
      for {
          // Read Messages
          _, _, err := conn.ReadMessage()
  
          if c, k := err.(*websocket.CloseError); k {
              if(c.Code == 1000) {
                  // Never entering since c.Code == 1005
                  fmt.Println(err)
                  break
              }
          }
      }
  }()
  
  conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(1000, "woops"))
  
  for {}
  </code></pre>
  
  <p>The server is reading the Close Frame as expected outputting the following:</p>
  
  <blockquote>
    <p>websocket: close 1000 (normal): woops</p>
  </blockquote>
  
  <p>However the client is like its stopping to read once it sends a close message. The <code>ReadMessage</code> continue to return error 1005. What am I doing wrong?</p>