Created
September 6, 2026 18:34
-
-
Save alexedwards/311dbedcf86695621ba649e75e3dd5e6 to your computer and use it in GitHub Desktop.
Example of streaming JSON objects in a HTTP response
This file contains hidden or 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
| 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