Skip to content

Commit 142603a

Browse files
committed
flush http response writer every chance to be able to stream write the response
1 parent de69d0b commit 142603a

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

main.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,10 +79,18 @@ func query(w http.ResponseWriter, r *http.Request) {
7979
return
8080
}
8181

82+
wFlusher, ok := w.(http.Flusher)
83+
if !ok {
84+
http.Error(w,
85+
fmt.Sprintf("Error creating a stream writer.\n\n%s", helpMessage), http.StatusInternalServerError)
86+
return
87+
}
88+
8289
w.Header().Set("Content-Type", "application/json")
8390
outpoutEncoder := json.NewEncoder(w)
8491
// start printing the outer array
8592
fmt.Fprintf(w, "[")
93+
wFlusher.Flush()
8694

8795
reqCsvReader := csv.NewReader(r.Body)
8896
reqCsvReader.ReuseRecord = true
@@ -101,6 +109,7 @@ func query(w http.ResponseWriter, r *http.Request) {
101109
if !isFirstQuery {
102110
// print comma between queries results
103111
fmt.Fprintf(w, ",")
112+
wFlusher.Flush()
104113
}
105114
isFirstQuery = false
106115

@@ -131,12 +140,14 @@ func query(w http.ResponseWriter, r *http.Request) {
131140
fmt.Fprintf(w, `"headers":`)
132141
outpoutEncoder.Encode(cols)
133142
fmt.Fprintf(w, `,"out":[`) // start printing the out rows array
143+
wFlusher.Flush()
134144

135145
isFirstRow := true
136146
for rows.Next() {
137147
if !isFirstRow {
138148
// print comma between rows
139149
fmt.Fprintf(w, ",")
150+
wFlusher.Flush()
140151
}
141152
isFirstRow = false
142153

@@ -166,10 +177,12 @@ func query(w http.ResponseWriter, r *http.Request) {
166177

167178
// finish printing a query result
168179
fmt.Fprintf(w, "]}")
180+
wFlusher.Flush()
169181
}
170182

171183
// finish printing the outer array
172184
fmt.Fprintf(w, "]\n")
185+
wFlusher.Flush()
173186
}
174187

175188
func buildHelpMessage() {

0 commit comments

Comments
 (0)