Stackademic

Stackademic is a learning hub for programmers, devs, coders, and engineers. Our goal is to democratize free coding education for the world.

Follow publication

Real-Time Communication with Golang and Server-Sent Events (SSE) — A Practical Tutorial

PRATHEESH PC
Stackademic
Published in
5 min readJun 12, 2023

--

Server-Sent Events with golang

What is SSE?

SSE stands for Server-Sent Events. It is a web technology that enables real-time communication between a web server and a client. SSE allows the server to send continuous streams of data to the client over a single HTTP connection, providing a simple and efficient way to deliver real-time updates, notifications, or event-driven information from the server to the client.

SSE uses a text-based format known as Event Stream, where each event consists of a specific event type, optional event data, and optional event ID. The server sends these events as a continuous stream, and the client can handle different events based on their types.

SSE Architectural diagram

Web Socket vs SSE

Unlike other real-time communication technologies like Web Sockets, SSE is a unidirectional communication channel where the server initiates the communication and sends data updates to the client. The client receives these updates as a stream of events and can take appropriate actions based on the received data.

SSE Headers

When using Server-Sent Events (SSE), the server sends a response with specific headers to establish and maintain the SSE connection.

Content-Type : The Content-Type header is set to text/event-stream. This indicates that the server is sending an SSE response, allowing the client to interpret the response as SSE data.

Cache-Control: The Cache-Control header is often set to no-cache. This instructs intermediate proxies and the client's browser not to cache the SSE response, ensuring that the client always receives real-time updates.

Connection: The Connection header is set to keep-alive. This tells the client and any intermediate proxies to keep the connection open for further SSE data.

Transfer-Encoding: SSE responses typically use Transfer-Encoding: chunked. It enables the server to send data in chunks, allowing the client to process data incrementally.

Stopping Event Stream

Once the appropriate data has been received, the connection must be closed and the event stream terminated. Depending on the client and server, there are two ways to do this.

At Client Side : The client can stop the events by calling the EventSource object’s .close() function. The server recognizes this approach and stops transmitting events to the client by closing the associated HTTP response.

At Server Side : The server can also terminate the event stream by delivering a last event with the end of stream event’s unique ID. The server can also halt the event stream by ending the HTTP response connection with the client.

Okay; Now that you have a basic understanding of SSE, let’s build it using Golang.

Let’s start with main.go

Endpoint

An endpoint is needed in the context of SSE (Server-Sent Events) to establish a connection between the client (typically a web browser) and the server. The endpoint serves as a URL that the client can send a request to in order to initiate the SSE communication.

Send Event

In the above code snippet, c.SSEvent("progress", ...) is used to send a Server-Sent Event (SSE) message with the event name "progress" and a payload containing various fields as key-value pairs.

c.Writer.Flush()

c.Writer refers to the underlying http.ResponseWriter associated with the HTTP request. It represents the response writer used to send the response back to the client.

It flush any buffered data and send it immediately to the client. It ensures that the data written so far is sent in the HTTP response without waiting for the entire response to be completed

And we send a progress complete response finally

The HTML, As we need an html page to display the progress bar

And the script

In JavaScript, the EventSource is a built-in browser API that allows the client-side code to establish a persistent and bi-directional connection to a server that supports Server-Sent Events (SSE).

Once the EventSource is created, it automatically starts receiving events from the server. The server sends events in the form of text-based data streams, which are parsed by the EventSource and trigger corresponding JavaScript event handlers. The EventSource object provides event listeners like onmessage, onopen, onerror, etc., to handle different events sent by the server.

Finally run the golang application by go run main.go and hit the url http://localhost:8080

Conclusion

SSE provides a lightweight and efficient mechanism for server-to-client real-time communication over HTTP, allowing web applications to deliver real-time updates without the need for constant client polling.

This go application demonstrates the implementation of Server-Sent Events (SSE) for real-time communication between the server and clients. SSE allows the server to push updates to the clients over a long-lived HTTP connection, enabling real-time data streaming.

The Go application sets up an SSE endpoint and sends periodic progress updates to the connected clients. The c.SSEvent() function is used to send SSE events with custom data fields.

Clients can establish an SSE connection using JavaScript’s EventSource API. The client-side JavaScript code creates an EventSource object, listens for events such as progress, and handles the received updates accordingly.

Overall, the power and simplicity of SSE can be used for real-time communication, making it suitable for various use cases such as live data updates, progress tracking, and real-time notifications.

I hope this article helps. Thank you so much for reading. :)

by me a coffe

If you enjoy my articles or find value in what I write, consider supporting my work by buying me a coffee! ☕️

👉Also learn how to manage IoT devices using Golang’s GoFr and MQTT:

Stackademic 🎓

Thank you for reading until the end. Before you go:

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Published in Stackademic

Stackademic is a learning hub for programmers, devs, coders, and engineers. Our goal is to democratize free coding education for the world.

Written by PRATHEESH PC

Hey there! I'm a software developer and I'm absolutely in love with building things with technology.

Write a response