|
| 1 | +package xNdJson |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "net/http" |
| 6 | + "time" |
| 7 | +) |
| 8 | + |
| 9 | +func pushEvents(rw http.ResponseWriter, events [][]string) { |
| 10 | + for _, event := range events { |
| 11 | + for _, line := range event { |
| 12 | + fmt.Fprint(rw, line) |
| 13 | + } |
| 14 | + |
| 15 | + if f, ok := rw.(http.Flusher); ok { |
| 16 | + f.Flush() |
| 17 | + } |
| 18 | + |
| 19 | + time.Sleep(100 * time.Millisecond) |
| 20 | + } |
| 21 | +} |
| 22 | + |
| 23 | +func pushChunks(rw http.ResponseWriter, chunks []string) { |
| 24 | + for _, chunk := range chunks { |
| 25 | + fmt.Fprint(rw, chunk) |
| 26 | + |
| 27 | + if f, ok := rw.(http.Flusher); ok { |
| 28 | + f.Flush() |
| 29 | + } |
| 30 | + |
| 31 | + time.Sleep(100 * time.Millisecond) |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +func HandleXNdJsonLinesChunksRich(rw http.ResponseWriter, _ *http.Request) { |
| 36 | + rw.Header().Add("Content-Type", "application/x-ndjson") |
| 37 | + |
| 38 | + pushChunks(rw, []string{ |
| 39 | + "{\"name\": \"Peter\", \"skills\": [\"Go\"", |
| 40 | + ", \"Python\"]}\n{\"name\": \"John\"", |
| 41 | + ", \"skills\": [\"Go\", \"Rust\"]}\n", |
| 42 | + }) |
| 43 | +} |
| 44 | + |
| 45 | +func HandleXNdJsonLinesRich(rw http.ResponseWriter, _ *http.Request) { |
| 46 | + rw.Header().Add("Content-Type", "application/x-ndjson") |
| 47 | + |
| 48 | + pushEvents(rw, [][]string{ |
| 49 | + { |
| 50 | + "{\"name\": \"Peter\", \"skills\": [\"Go\", \"Python\"]}\n", |
| 51 | + }, |
| 52 | + { |
| 53 | + "{\"name\": \"John\", \"skills\": [\"Go\", \"Rust\"]}\n", |
| 54 | + }, |
| 55 | + }) |
| 56 | +} |
0 commit comments