sse is a lightweight Go library for writing Server-Sent Events (SSE). This library allows easy integration of SSE into web servers, providing real-time updates to connected clients.
To install the sse package, use the following command:
go get github.com/floriscornel/sseimport (
"net/http"
"github.com/floriscornel/sse"
)To create an SSE writer, use the NewResponseWriter function. This function requires an http.ResponseWriter and options to configure the SSE writer.
opts := sse.Options{
ResponseStatus: http.StatusOK,
Encoding: sse.EncodeNone,
}
func handler(w http.ResponseWriter, r *http.Request) {
sseWriter := sse.NewResponseWriter(w, opts)
for {
err := sseWriter.Write("message", map[string]string{"hello": "world"})
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
time.Sleep(2 * time.Second)
}
}
http.HandleFunc("/events", handler)
log.Fatal(http.ListenAndServe(":8080", nil))The sse package supports various encoding options to compress the data sent to clients. Available encoding options include:
EncodeNoneEncodeDeflateEncodeCompressEncodeGzipEncodeBrotliEncodeZstd
Specify the desired encoding in the Options struct:
opts := sse.Options{
ResponseStatus: http.StatusOK,
Encoding: sse.EncodeGzip,
}You can find more examples in the examples directory. To run an example, navigate to the respective directory and execute the following command:
go run main.goping: A simple example of sending periodic ping messages to the client.incremental-updates: Demonstrates sending incremental updates to the client with different event types.number-of-listeners: Implements a counter to track the number of connected clients.
Contributions are welcome! Feel free to open issues or submit pull requests. For major changes, please open an issue first to discuss what you would like to change.
This project is licensed under the MIT License. See the LICENSE file for details.
If you have any questions, feel free to reach out:
- Author: Floris Cornel
- Email: [email protected]
- GitHub: github.com/floriscornel/sse