DEV Community

Cover image for Websockets in Golang under 5 Minutes.
Akshansh Gusain
Akshansh Gusain

Posted on

Websockets in Golang under 5 Minutes.

#go

Lets start with a simple http endpoint.

Start off by building a simple HTTP server that returns Hello Devs whenever we hit it on port 8001. We’ll also define a simple HTTP endpoint that will act as the base of the WebSocket endpoint that we’ll be creating:

Image description

Upgrading the HTTP Connection

To create a WS endpoint we need to upgrade a standard HTTP connection to a WS connection. We'll be using gorilla/websocket package for this.

1. Define the Upgrader

This will hold information such as the Read and Write buffer size for our WS connection:

Image description

2. Take care of the CORS

This will determine whether or not an incoming request from a different domain is allowed to connect, and if it isn’t they’ll be hit with a CORS error. For now, we'll simply return true.

Image description

3. Upgrading the Connection

We can now start attempting to upgrade the incoming HTTP connection using the upgrader.Upgrade() function which will take in the Response Writer and the pointer to the HTTP Request and return us with a pointer to a WebSocket connection, or an error if it failed to upgrade.

Image description

Start Listening

Once the client is connected we can pass our WS to a reader function.

Image description

*A simple echo reader: *
A simple reader function that echos back every incoming message:

Image description

And that's it! We just created a WS endpoint in Go.

Further reading:

https://www.freecodecamp.org/news/million-websockets-and-go-cc58418460bb/

Find the code here:
https://gist.github.com/akshanshgusain/f2a797bc593136fd3484edb6d7401c50

Top comments (0)