Skip to content

Commit

Permalink
Refactor the flush behavior, and make sure that a status code is set
Browse files Browse the repository at this point in the history
  • Loading branch information
xyproto committed Sep 30, 2024
1 parent f9858be commit 57aa672
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
24 changes: 19 additions & 5 deletions engine/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ import (
"github.com/xyproto/algernon/utils"
"github.com/xyproto/datablock"
"github.com/xyproto/ollamaclient/v2"
"github.com/xyproto/recwatch"
"github.com/xyproto/sheepcounter"
"github.com/xyproto/simpleform"
"github.com/xyproto/unzip"
Expand Down Expand Up @@ -284,8 +283,18 @@ func (ac *Config) FilePage(w http.ResponseWriter, req *http.Request, filename, l
httpStatus := &FutureStatus{}
// The flush function writes the ResponseRecorder to the ResponseWriter
flushFunc := func() {
utils.WriteRecorder(w, recorder)
recwatch.Flush(w)
// If things went well, check if there is a status code we should write first
// (especially for the case of a redirect)
if httpStatus.code != 0 {
recorder.WriteHeader(httpStatus.code)
} else {
recorder.WriteHeader(http.StatusOK)
}
// Then write to the ResponseWriter
utils.WriteRecorder(w, recorder) // WriteRecorder starts out by writing the status header
if flusher, ok := w.(http.Flusher); ok {
flusher.Flush()
}
}
// Run the lua script, without the possibility to flush
if err := ac.RunLua(recorder, req, filename, flushFunc, httpStatus); err != nil {
Expand All @@ -304,14 +313,19 @@ func (ac *Config) FilePage(w http.ResponseWriter, req *http.Request, filename, l
// (especially for the case of a redirect)
if httpStatus.code != 0 {
recorder.WriteHeader(httpStatus.code)
} else {
recorder.WriteHeader(http.StatusOK)
}
// Then write to the ResponseWriter
utils.WriteRecorder(w, recorder)
utils.WriteRecorder(w, recorder) // WriteRecorder starts out by writing the status header
}
} else {
// The flush function just flushes the ResponseWriter
flushFunc := func() {
recwatch.Flush(w)
w.WriteHeader(http.StatusOK)
if flusher, ok := w.(http.Flusher); ok {
flusher.Flush()
}
}
// Run the lua script, with the flush feature
if err := ac.RunLua(w, req, filename, flushFunc, nil); err != nil {
Expand Down
6 changes: 5 additions & 1 deletion utils/recorders.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,11 @@ func WriteRecorder(w http.ResponseWriter, recorder *httptest.ResponseRecorder) i
w.Header().Set(key, value)
}
}
w.WriteHeader(recorder.Result().StatusCode)
if statusCode := recorder.Result().StatusCode; statusCode == 0 {
w.WriteHeader(http.StatusOK)
} else {
w.WriteHeader(statusCode)
}
bytesWritten, err := recorder.Body.WriteTo(w)
if err != nil {
// Writing failed
Expand Down

0 comments on commit 57aa672

Please sign in to comment.