echo icon indicating copy to clipboard operation
echo copied to clipboard

Improved robustness of Response process and added debugging information

Open suwakei opened this issue 7 months ago • 0 comments

Overview

The following improvements have been made to the WriteHeader and Flush methods of response.go:

1.Check for logger presence in WriteHeader: Before calling r.echo. Make sure that r.echoandr.echo.Loggerare notnilbefore callingr.echo.Logger.Warn`. This reduces the risk of panic due to unexpected nil pointer references.

2.Additional error logging in Flush: Additional error logging in http. If http.ResponseController.Flush()returns an error other thanhttp.ErrNotSupported, log the error if in debug mode (r.echo.Debug == true). This additional logging is useful for debugging during development, since the Flushmethod of thehttp.Flusherinterface is by convention not to return errors, but theResponseController` may.

Changes

response.go

@@ -26,7 +26,9 @@
 // used to send error codes.
 func (r *Response) WriteHeader(code int) {
 	if r.Committed {
-		r.echo.Logger.Warn("response already committed")
+		if r.echo != nil && r.echo.Logger != nil {
+			r.echo.Logger.Warn("response already committed")
+		}
 		return
 	}
 	r.Status = code
@@ -49,12 +51,15 @@
 // See [http.Flusher](https://golang.org/pkg/net/http/#Flusher)
 func (r *Response) Flush() {
 	err := http.NewResponseController(r.Writer).Flush()
-	if err != nil && errors.Is(err, http.ErrNotSupported) {
-		panic(errors.New("response writer flushing is not supported"))
+	if err != nil {
+		if errors.Is(err, http.ErrNotSupported) {
+			panic(errors.New("response writer flushing is not supported"))
+		}
+		// Log other flush errors if a logger is available and in debug mode,
+		// as http.Flusher interface does not allow returning an error.
+		if r.echo != nil && r.echo.Logger != nil && r.echo.Debug {
+			r.echo.Logger.Errorf("error during response flush: %v", err)
+		}
 	}
 }

Expected Effects

  • Improve stability by eliminating the possibility of nil pointer references in WriteHeader.

  • Improves development efficiency by providing detailed information in debug mode about unexpected errors during flushing.

suwakei avatar Jun 18 '25 11:06 suwakei