diff --git a/context.go b/context.go index 9be52f0aa..2bb66d232 100644 --- a/context.go +++ b/context.go @@ -660,17 +660,68 @@ func (c *Context) JSONPBlob(code int, callback string, b []byte) (err error) { return } -func (c *Context) xml(code int, i any, indent string) (err error) { - c.writeContentType(MIMEApplicationXMLCharsetUTF8) - c.response.WriteHeader(code) - enc := xml.NewEncoder(c.response) +func (c *Context) xml(code int, i any, indent string) error { + // encoding/xml can fail before it writes. Hold the status until the first + // byte or an HTTP flush, and write the declaration with that byte, so the + // error handler can still respond. A flush commits the XML content type + // with the status. A flush that already wrote keeps that response. + resp := c.Response() + if _, nested := resp.(*delayedStatusWriter); nested { + c.SetResponse(&delayedStatusWriter{ResponseWriter: resp, status: code, contentType: MIMEApplicationXMLCharsetUTF8}) + } else { + c.dsw = delayedStatusWriter{ResponseWriter: resp, status: code, contentType: MIMEApplicationXMLCharsetUTF8} + c.SetResponse(&c.dsw) + } + defer c.SetResponse(resp) + + out := &xmlDeclarationWriter{w: c.response} + enc := xml.NewEncoder(out) if indent != "" { enc.Indent("", indent) } - if _, err = c.response.Write([]byte(xml.Header)); err != nil { - return + if err := enc.Encode(i); err != nil { + return err + } + if !out.wrote { + // Encode succeeded and wrote nothing, which is what a nil value does. + // Keep the previous success output: the requested status and the declaration. + return out.writeDeclaration() + } + return nil +} + +// xmlDeclarationWriter writes the XML declaration before the first byte from the encoder. +type xmlDeclarationWriter struct { + w http.ResponseWriter + wrote bool +} + +func (x *xmlDeclarationWriter) Write(p []byte) (int, error) { + if len(p) == 0 { + return 0, nil + } + if err := x.writeDeclaration(); err != nil { + return 0, err + } + return x.w.Write(p) +} + +func (x *xmlDeclarationWriter) writeDeclaration() error { + if x.wrote { + return nil } - return enc.Encode(i) + if x.w.Header().Get(HeaderContentType) == "" { + x.w.Header().Set(HeaderContentType, MIMEApplicationXMLCharsetUTF8) + } + n, err := x.w.Write([]byte(xml.Header)) + if err != nil { + return err + } + if n < len(xml.Header) { + return io.ErrShortWrite + } + x.wrote = true + return nil } // XML sends an XML response with status code. diff --git a/context_test.go b/context_test.go index 9b2b59e99..8bf33552b 100644 --- a/context_test.go +++ b/context_test.go @@ -447,6 +447,131 @@ func TestContextXMLBlob(t *testing.T) { } } +func TestContextXMLErrorsOut(t *testing.T) { + e := New() + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/", nil) + c := e.NewContext(req, rec) + + err := c.XML(http.StatusAccepted, map[string]string{"title": "example"}) + assert.Error(t, err) + assert.Equal(t, http.StatusOK, rec.Code) // status code must not be sent to the client + assert.Empty(t, rec.Body.String()) + assert.Empty(t, rec.Header().Get(HeaderContentType)) +} + +func TestContextXMLNilWritesDeclaration(t *testing.T) { + e := New() + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/", nil) + c := e.NewContext(req, rec) + + err := c.XML(http.StatusAccepted, nil) + assert.NoError(t, err) + assert.Equal(t, http.StatusAccepted, rec.Code) + assert.Equal(t, MIMEApplicationXMLCharsetUTF8, rec.Header().Get(HeaderContentType)) + assert.Equal(t, xml.Header, rec.Body.String()) +} + +func TestContextXMLEncodeErrorReachesErrorHandler(t *testing.T) { + e := New() + e.GET("/", func(c *Context) error { + return c.XML(http.StatusAccepted, map[string]string{"title": "example"}) + }) + + rec := httptest.NewRecorder() + e.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil)) + assert.Equal(t, http.StatusInternalServerError, rec.Code) + assert.Equal(t, MIMEApplicationJSON, rec.Header().Get(HeaderContentType)) + assert.JSONEq(t, `{"message":"Internal Server Error"}`, rec.Body.String()) +} + +func TestContextXMLPrettyEncodeErrorReachesErrorHandler(t *testing.T) { + e := New() + e.GET("/", func(c *Context) error { + return c.XMLPretty(http.StatusAccepted, map[string]string{"title": "example"}, " ") + }) + + rec := httptest.NewRecorder() + e.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil)) + assert.Equal(t, http.StatusInternalServerError, rec.Code) + assert.Equal(t, MIMEApplicationJSON, rec.Header().Get(HeaderContentType)) + assert.JSONEq(t, `{"message":"Internal Server Error"}`, rec.Body.String()) +} + +type xmlFlushThenFail struct{} + +func (xmlFlushThenFail) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + if err := enc.EncodeToken(start); err != nil { + return err + } + if err := enc.EncodeToken(xml.CharData("partial")); err != nil { + return err + } + if err := enc.EncodeToken(xml.EndElement{Name: start.Name}); err != nil { + return err + } + if err := enc.Flush(); err != nil { + return err + } + return errors.New("after flush") +} + +func TestContextXMLErrorAfterFlushKeepsWrittenResponse(t *testing.T) { + e := New() + e.GET("/", func(c *Context) error { + return c.XML(http.StatusAccepted, xmlFlushThenFail{}) + }) + + rec := httptest.NewRecorder() + e.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil)) + assert.Equal(t, http.StatusAccepted, rec.Code) + assert.Equal(t, MIMEApplicationXMLCharsetUTF8, rec.Header().Get(HeaderContentType)) + assert.Contains(t, rec.Body.String(), xml.Header) + assert.Contains(t, rec.Body.String(), "partial") + assert.NotContains(t, rec.Body.String(), "Internal Server Error") +} + +// xmlHTTPFlushThenElement flushes the HTTP response before the encoder writes an element. +// That is a different boundary from enc.Flush, which already wrote the declaration. +type xmlHTTPFlushThenElement struct { + c *Context +} + +func (x xmlHTTPFlushThenElement) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + http.NewResponseController(x.c.Response()).Flush() + if err := enc.EncodeToken(start); err != nil { + return err + } + if err := enc.EncodeToken(xml.CharData("ok")); err != nil { + return err + } + if err := enc.EncodeToken(xml.EndElement{Name: start.Name}); err != nil { + return err + } + return enc.Flush() +} + +func TestContextXMLHTTPFlushPinsContentType(t *testing.T) { + e := New() + e.GET("/", func(c *Context) error { + return c.XML(http.StatusAccepted, xmlHTTPFlushThenElement{c: c}) + }) + + rec := httptest.NewRecorder() + e.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil)) + + res := rec.Result() + defer res.Body.Close() + assert.Equal(t, http.StatusAccepted, res.StatusCode) + assert.Equal(t, MIMEApplicationXMLCharsetUTF8, res.Header.Get(HeaderContentType)) + body, err := io.ReadAll(res.Body) + assert.NoError(t, err) + assert.Contains(t, string(body), xml.Header) + assert.Contains(t, string(body), "ok") + assert.NotContains(t, string(body), "Internal Server Error") +} + func TestContextXMLWithEmptyIntent(t *testing.T) { e := New() rec := httptest.NewRecorder() diff --git a/response.go b/response.go index e6adea77c..4bd04c7ce 100644 --- a/response.go +++ b/response.go @@ -175,10 +175,20 @@ func supportsFlush(rw http.ResponseWriter) bool { // delayedStatusWriter is a wrapper around http.ResponseWriter that delays writing the status code until first Write is called. // This allows (global) error handler to decide correct status code to be sent to the client. +// contentType, when set, is applied at that same commit, including an explicit Flush before any Write. +// Leave it empty when the caller already set the header, as JSON does. type delayedStatusWriter struct { http.ResponseWriter - committed bool - status int + committed bool + status int + contentType string +} + +func (w *delayedStatusWriter) ensureContentType() { + if w.contentType == "" || w.Header().Get(HeaderContentType) != "" { + return + } + w.Header().Set(HeaderContentType, w.contentType) } func (w *delayedStatusWriter) WriteHeader(statusCode int) { @@ -187,12 +197,16 @@ func (w *delayedStatusWriter) WriteHeader(statusCode int) { return } // in case something else writes status code explicitly before us we need mark response committed + if !w.committed { + w.ensureContentType() + } w.committed = true w.ResponseWriter.WriteHeader(statusCode) } func (w *delayedStatusWriter) Write(data []byte) (int, error) { if !w.committed { + w.ensureContentType() w.committed = true if w.status == 0 { w.status = http.StatusOK @@ -204,7 +218,8 @@ func (w *delayedStatusWriter) Write(data []byte) (int, error) { func (w *delayedStatusWriter) Flush() { if !w.committed && supportsFlush(w.ResponseWriter) { - // Flushing sends the headers, so send the delayed status first. + // Flushing sends the headers, so send the delayed status and content type first. + w.ensureContentType() w.committed = true if w.status == 0 { w.status = http.StatusOK