Mastering WebSockets With Go

<p>If we think about it, regular HTTP APIs are dumb, like, really dumb. We can fetch data by sending a request for the data. If we have to keep data fresh on a website, we will have to continuously request the data, so-called Polling.</p> <blockquote> <p>All Images in this article is made by Percy Bolm&eacute;r. Gopher by Takuya Ueda, Original Go Gopher by Ren&eacute;e French (CC BY 3.0)</p> </blockquote> <p>This is like having a kid in the backseat asking &ldquo;Are we there yet&rdquo;, instead of having the driver say &ldquo;We are there now&rdquo;. This is the way we started to use when designing websites, Silly isn&rsquo;t it?</p> <p>Thankfully, developers have solved this with technologies like&nbsp;<a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API" rel="noopener ugc nofollow" target="_blank">WebSockets</a>,&nbsp;<a href="https://webrtc.org/" rel="noopener ugc nofollow" target="_blank">WebRTC</a>,&nbsp;<a href="https://grpc.io/" rel="noopener ugc nofollow" target="_blank">gRPC</a>,&nbsp;<a href="https://web.dev/performance-http2/" rel="noopener ugc nofollow" target="_blank">HTTP2 Stream</a>,&nbsp;<a href="https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events" rel="noopener ugc nofollow" target="_blank">ServerSent Events</a>, and other bi-directional communications.</p> <p>WebSockets is one of the oldest ways to communicate in a bi-directional way and is widely used today. It is supported by most browsers and is relatively easy to use.</p> <p>In this tutorial, we will cover what WebSockets are and how they work, how to use them in Go to communicate between servers and clients. We will also explore some regular pitfalls that I&rsquo;ve seen in WebSocket APIs, and how to solve them.</p> <p>During the tutorial, we will be building a chat application where you can enter different chat rooms. The WebSocket server will be built using Go, and the client connecting in vanilla JavaScript. The patterns we learn and apply could easily be adapted when connecting using a Websocket Client written in Go, Java, React, or any other language.</p> <p><a href="https://towardsdatascience.com/mastering-websockets-with-go-c30d0ac48081">Website</a></p>