DEV Community

Cover image for Server-Sent Events in Go: An efficient real-time communication alternative
Gustavo Castillo
Gustavo Castillo

Posted on

Server-Sent Events in Go: An efficient real-time communication alternative

#go

Original posted in my website

Introduction

In today's software engineering landscape, real-time communication plays a crucial role in many modern applications. One technology that has gained popularity in this realm is Server-Sent Events (SSE).

In this article, we will explore what Server-Sent Events are, compare their features to WebSockets, provide a code example in Go and JavaScript, discuss the advantages and disadvantages of using Server-Sent Events, and draw a conclusion about their utility in general.

What are Server-Sent Events?

Server-Sent Events is a technology that allows servers to asynchronously send data to clients through a persistent HTTP connection. Unlike other real-time communication techniques like WebSockets, SSE utilizes a unidirectional connection from the server to the client.

This means that the client can only receive updates from the server without the ability to send data back directly.

WebSockets vs Server-Sent Events

While WebSockets and Server-Sent Events share the common goal of enabling real-time communication, there are key differences between them. WebSockets provide a bidirectional persistent connection, allowing both the client and server to send and receive data at any time.

On the other hand, SSE relies on a unidirectional connection, which limits communication solely from the server to the client. This difference makes SSE more suitable for use cases where data updates in real-time primarily originate from the server, such as news feeds or live events.

Code example

Here is a basic example showcasing the implementation of Server-Sent Events in Go and how to receive events in JavaScript.

server.go

package main

import (
  "fmt"
  "net/http"
  "time"
)

func main() {
  http.HandleFunc("/events", func(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "text/event-stream")
    w.Header().Set("Cache-Control", "no-cache")
    w.Header().Set("Connection", "keep-alive")
    w.Header().Set("Access-Control-Allow-Origin", "*")

    for {
      // Simulate sending events every second
      fmt.Fprintf(w, "data: %s\n\n", time.Now().Format(time.Stamp))
      w.(http.Flusher).Flush()
      time.Sleep(1 * time.Second)
    }
  })

  http.ListenAndServe(":8080", nil)
}
Enter fullscreen mode Exit fullscreen mode

client.html

<script>
  const eventSource = new EventSource('http://localhost:8080/events')

  eventSource.onmessage = function (event) {
    console.log('Message received: ', event.data)
  }

  eventSource.onerror = function (event) {
    console.error('An error occurred:', event)
  }
</script>
Enter fullscreen mode Exit fullscreen mode

Advantages

  • Simplicity: Server-Sent Events utilize an event-based interface that is easy to implement both on the server and client sides.
  • Compatibility: SSE is supported by all modern browsers, making it an accessible choice for developers.
  • Efficiency: Unlike WebSockets, SSE employs a standard HTTP connection, avoiding the additional overhead associated with establishing and maintaining a WebSocket connection. This can result in more efficient utilization of server resources.

Disadvantages

  • Unidirectional communication: SSE only allows communication in one direction, limiting its usage in scenarios that require constant bidirectional interaction between the client and server.
  • Limited support in older browsers: While modern browsers fully support SSE, older browsers may offer incomplete or no support at all. This restricts the target audience of the application.
  • Lack of error control: In SSE, if the connection is lost, the client will automatically attempt to reconnect. However, more advanced error handling and connection recovery must be implemented manually.

On Server-Sent Events

Server-Sent Events provide an effective and efficient option for implementing real-time communication in web applications. Their simplicity, compatibility, and efficiency are notable highlights that make them appealing for certain use cases.

However, their unidirectional nature and limitations in support for older browsers may influence the choice of using SSE compared to other alternatives like WebSockets. As with any technology, it is crucial to carefully evaluate the application requirements and project needs before deciding which real-time communication approach to employ.

Conclusion

In summary, Server-Sent Events are a valuable and viable choice for implementing real-time communication in web applications, offering an efficient and user-friendly solution in scenarios where unidirectional communication suffices, and modern browser support is a priority.

Top comments (2)

Collapse
 
der_gopher profile image
Alex Pliutau

Great write up! Does anyone use Server-Sent Events in their projects? If yes, for which use cases? This video dives into the main building blocks of Server-Sent Events in Go.
youtu.be/nvijc5J-JAQ

Collapse
 
dyfet profile image
David Sugar

Sometimes your goal is to be able to receive event notifications within the context of an otherwise rpc-style web service. This would seem ideal for that purpose.