Skip to content

Commit

Permalink
fix: infinite recursion bug (#20862)
Browse files Browse the repository at this point in the history
* Revert "fix(error): unsupported value: +Inf" error not handled gracefully (#20250)"

This reverts commit 6ac0bb3.

* fix: No infinite recursion on write error

If there is some error writing to the response writer, we
would previous have infinite recursion.

Re-closes #20249

(cherry picked from commit d6f7716)
  • Loading branch information
lesam authored and davidby-influx committed Mar 6, 2021
1 parent b2cb862 commit d1929f5
Showing 1 changed file with 21 additions and 11 deletions.
32 changes: 21 additions & 11 deletions services/httpd/response_writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,13 +98,9 @@ func (w *bytesCountWriter) Write(data []byte) (int, error) {

// WriteResponse writes the response using the formatter.
func (w *responseWriter) WriteResponse(resp Response) (int, error) {
n := 0
writer := bytesCountWriter{w: w.ResponseWriter}
err := w.formatter.WriteResponse(&writer, resp)
if err != nil {
n, _ = WriteError(w, err)
}
return writer.n + n, err
return writer.n, err
}

// Flush flushes the ResponseWriter if it has a Flush() method.
Expand All @@ -127,21 +123,35 @@ type jsonFormatter struct {
Pretty bool
}

func (f *jsonFormatter) WriteResponse(w io.Writer, resp Response) (err error) {
func (f *jsonFormatter) WriteResponse(w io.Writer, resp Response) error {
var b []byte

var err error
if f.Pretty {
b, err = json.MarshalIndent(resp, "", " ")
} else {
b, err = json.Marshal(resp)
}

if err != nil {
err = unnestError(err)
} else if _, err = w.Write(b); err == nil {
_, err = w.Write([]byte("\n"))
unnestedErr := unnestError(err)
// ignore any errors in this section, we already have a 'real' error to return
resp := Response{Err: unnestedErr}
if f.Pretty {
b, _ = json.MarshalIndent(resp, "", " ")
} else {
b, _ = json.Marshal(resp)
}
w.Write(b)
w.Write([]byte("\n"))
return err
}

_, err = w.Write(b)
if err != nil {
return err
}
return
_, err = w.Write([]byte("\n"))
return err
}

func unnestError(err error) error {
Expand Down

0 comments on commit d1929f5

Please sign in to comment.