Skip to content

Conversation

@raju-mechatronics
Copy link

Bug Fix

Problem

The json() method in context.go (line 504) was inconsistent with other response methods in how it sets the HTTP status code.

Current behavior:

func (c *context) json(code int, i any, indent string) error {
    c.writeContentType(MIMEApplicationJSON)
    c.response.Status = code  // ❌ Directly setting Status field
    return c.echo.JSONSerializer.Serialize(c, i, indent)
}

This approach directly sets the Status field instead of properly calling WriteHeader(), which bypasses header commitment and prevents warnings about header modifications after the status is set.

Solution

Updated the method to use c.response.WriteHeader(code) for consistency with other response methods:

func (c *context) json(code int, i any, indent string) error {
    c.writeContentType(MIMEApplicationJSON)
    c.response.WriteHeader(code)  // ✅ Properly calls WriteHeader
    return c. echo.JSONSerializer.Serialize(c, i, indent)
}

All other similar response methods already use WriteHeader():

  • jsonPBlob() - line 489: c.response.WriteHeader(code)
  • xml() - line 543: c.response.WriteHeader(code)
  • Blob() - line 578: c.response.WriteHeader(code)
  • JSONPBlob() - line 530: c.response.WriteHeader(code)

@raju-mechatronics
Copy link
Author

@aldas please take a look when you get a chance.

@aldas
Copy link
Contributor

aldas commented Jan 21, 2026

Hi, this is a "feature" that Echo uses. c.response.Status = code sets the code for status, which will be used with next responseWriter.Write call and until there have not been "Write" calls the echo.JSONSerializer.Serialize implementation can decide to use different status code.

I really do not want to touch this part as it could introduce subtle bugs for people that rely on this "feature".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants