Skip to content

Instantly share code, notes, and snippets.

@alexedwards
Created September 6, 2026 18:34
Show Gist options
  • Select an option

  • Save alexedwards/311dbedcf86695621ba649e75e3dd5e6 to your computer and use it in GitHub Desktop.

Select an option

Save alexedwards/311dbedcf86695621ba649e75e3dd5e6 to your computer and use it in GitHub Desktop.
Example of streaming JSON objects in a HTTP response
func (app *application) exampleHandler(w http.ResponseWriter, r *http.Request) {
enc := jsontext.NewEncoder(w)
rc := http.NewResponseController(w)
w.Header().Set("Content-Type", "application/x-ndjson")
for i := range 5 {
data := map[string]int{
"count": i,
}
err := json.MarshalEncode(enc, data, json.Deterministic(true))
if err != nil {
if i == 0 {
http.Error(w, "The server encountered a problem and could not process your request", http.StatusInternalServerError)
}
app.logger.Error(err.Error())
return
}
err = rc.Flush()
if err != nil {
app.logger.Error(err.Error())
return
}
time.Sleep(time.Second)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment