Server-Sent Event In Golang

Let’s talk about SSE and implement it with golang.

Muhammad Isa
3 min readJul 5, 2021

About Server-Sent Event

SSE is unidirectional data transfer mechanism from the server to the client, that you need to perform GET request with Content-Type as text/event-stream, for tells the server you need to established server event channel and the server will keeps send you data changes, when you trigger an event.

Parable

Server-Sent Event is like waiters in restaurant, when you ask for order they will serve anything you ask for, until you are done.

That proved to be used full for use cases like.

  • Live Feeds : when you need to retrieve feeds data in real time.
  • Events : when you need to retrieve data when specific event was triggered.
  • Polling : when you need to retrieve data when there is a change.

Why not using WebSocket?

If you need bidirectional communication you can use websocket, even websocket can be used for unidirectional, but SSE is much simpler for communication with one direction (unidirectional).

Make SSE Server with Go

You can just copy this code into main.go for start learning how SSE works, after that you can read the code.

Once the server successfully running, you can test it via google chrome that will pretend like client side, and listen for data through stream endpoint that we have configured as SSE stream.

Using Google Chrome console for client

We use google chrome console, because its more representing server and client, (SSE) acting as the server & (google chrome console) acting as the client. you can start with this JavaScript code.

JavaScript code for SSE Client in google chrome console

After that you can test sending data with “/send”, “/left”, “/right” endpoint, for seeing data will be printed using console.log.

1st try we will use “curl http://localhost:8080/send”

2nd try we will use “curl http://localhost:8080/left”

3rd try we will use “curl http://localhost:8080/right”

Conclusion

As you can see the value of data that google chrome console received from “/stream” endpoint is different every time we call 3 different endpoints, you can do the same like google chrome console does inside React.js framework using axios, or other programming language.

And SSE server is only can handle one client and cannot be more, because the purpose of SSE is just to send data depends on events (endpoint) that we trigger through http request.

Hopping this will help you develop your project :) feel free to share.

Thanks a lot.

--

--