Created
January 26, 2024 09:45
-
-
Save keegancsmith/4e133d976f7042f0b56b6f1f062dae7b to your computer and use it in GitHub Desktop.
SSE with gzip in go playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8" /> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge" /> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> | |
<title>SSE</title> | |
</head> | |
<body onload="onLoaded()"> | |
<h1>Server Sent Events</h1> | |
<div id="main"> | |
<h3 id="rand-container">Random Number</h3> | |
<div id="random-number"></div> | |
</div> | |
<script> | |
const onLoaded = () => { | |
let eventSource = new EventSource("/random"); | |
eventSource.onmessage = (event) => { | |
document.getElementById("random-number").innerHTML = event.data; | |
}; | |
}; | |
</script> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"embed" | |
_ "embed" | |
"fmt" | |
"log" | |
"math/rand" | |
"net/http" | |
"time" | |
"github.com/NYTimes/gziphandler" | |
streamhttp "github.com/sourcegraph/sourcegraph/internal/search/streaming/http" | |
) | |
//go:embed index.html | |
var indexFS embed.FS | |
func main() { | |
http.Handle("/", http.FileServer(http.FS(indexFS))) | |
// default gzipMiddleware buffers small events | |
//gzipMiddleware := gziphandler.GzipHandler | |
gzipMiddleware, err := gziphandler.GzipHandlerWithOpts(gziphandler.MinSize(0)) | |
if err != nil { | |
panic(err) | |
} | |
http.Handle("/random", gzipMiddleware(http.HandlerFunc(randomHandler))) | |
log.Fatal(http.ListenAndServe(":8080", nil)) | |
} | |
func randomHandler(w http.ResponseWriter, r *http.Request) { | |
streamWriter, err := streamhttp.NewWriter(w) | |
if err != nil { | |
panic(err) | |
} | |
// send a random number every 2 seconds | |
for { | |
n := rand.Intn(100) | |
log.Println(n) | |
data := fmt.Sprintf("%d ", n) | |
// uncomment below to force large event payloads. Without this default | |
// gzip handler blocks. | |
//data = strings.Repeat(data, 1000) | |
err := streamWriter.Event("", data) | |
if err != nil { | |
return | |
} | |
time.Sleep(2 * time.Second) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment