DEV Community

Cover image for Server Sent Events in Go
Gurleen Sethi
Gurleen Sethi

Posted on

Server Sent Events in Go

👉 Read the complete article on TheDeveloperCafe

Introduction

In this article, I will demonstrate how to set up a basic SSE (Server Sent Events) endpoint in Go. The complete code related to this article is available in this GitHub repository.

Example: We are going to assume an example of a live crypto price api.

Project Setup

Initialize a new go project.

mkdir go-server-send-events-examples
cd go-server-send-events-examples
go mod init github.com/gurleensethi/go-server-send-events-examples
Enter fullscreen mode Exit fullscreen mode

Create a main.go file with basic http server setup.

package main

import (
    "net/http"
)

func main() {
    http.ListenAndServe(":4444", nil)
}
Enter fullscreen mode Exit fullscreen mode

Mocking live data

Write a function that generates random integers every second. This function will simulate live crypto price data that you will send back to the client.

func main() {
    ...
}

// generateCryptoPrice generates price as random integer and sends it the
// provided channel every 1 second.
func generateCryptoPrice(ctx context.Context, priceCh chan<- int) {
    r := rand.New(rand.NewSource(time.Now().Unix()))

    ticker := time.NewTicker(time.Second)

outerloop:
    for {
        select {
        case <-ctx.Done():
            break outerloop
        case <-ticker.C:
            p := r.Intn(100)
            priceCh <- p
        }
    }

    ticker.Stop()

    close(priceCh)
}
Enter fullscreen mode Exit fullscreen mode

The generateCryptoPrice function accepts a one-way write-only channel to which it sends the live price. It uses time.Ticker with a duration of 1 second to send a price update.

Furthermore, we receive a context that we can use to stop sending price updates. For instance, if the client disconnects, the context is cancelled, and price updates cease.

math/rand package is used to generate random integers.

...

👉 Read the complete article on TheDeveloperCafe

Top comments (0)