gin icon indicating copy to clipboard operation
gin copied to clipboard

serveError does not call WriteHeader() before calling Write()

Open melugoyal opened this issue 1 year ago • 3 comments

Description

Gin should call c.Writer.WriteHeader(code) before calling c.Writer.Write(defaultMessage) when handling errors here: https://github.com/gin-gonic/gin/blob/b04917c53e310e3746ec90cd93106cda8c956211/gin.go#L658

from the documentation of the Write() function in net/http's ResponseWriter interface:

If WriteHeader has not yet been called, Write calls WriteHeader(http.StatusOK) before writing the data

This is an issue when injecting a custom response writer into Gin that needs to know the status that was written before Write is called. Otherwise the custom response writer defaults to 200 OK per the documentation above, then Gin later tries writing a different header with WriteHeaderNow().

Environment

  • go version: 1.18
  • gin version (or commit ref): 1.7.7 (issue is present on current master as well: b04917c53)

melugoyal avatar Aug 15 '22 23:08 melugoyal

To my understanding, the implementation of c.Writer is responseWriter, the responseWriter.Write will call the WriteHeader first.

mstmdev avatar Aug 16 '22 04:08 mstmdev

Right, but i am using a custom ResponseWriter with Gin (injected into the context), and when doing so, expect Gin to call WriteHeader before calling Write, as is documented in the interface godoc:

If WriteHeader is not called explicitly, the first call to Write will trigger an implicit WriteHeader(http.StatusOK). Thus explicit calls to WriteHeader are mainly used to send error codes

melugoyal avatar Aug 16 '22 04:08 melugoyal

I get it. It looks like it will break some existing conventions.

mstmdev avatar Aug 16 '22 05:08 mstmdev