MCPcopy
hub / github.com/labstack/echo / json

Method json

context.go:546–566  ·  view source on GitHub ↗
(code int, i any, indent string)

Source from the content-addressed store, hash-verified

544}
545
546func (c *Context) json(code int, i any, indent string) error {
547 c.writeContentType(MIMEApplicationJSON)
548
549 // as JSONSerializer.Serialize can fail, and in that case we need to delay sending status code to the client until
550 // (global) error handler decides correct status code for the error to be sent to the client.
551 // For that we need to use writer that can store the proposed status code until the first Write is called.
552 resp := c.Response()
553 // Reuse the Context-owned delayedStatusWriter to avoid heap-allocating one per JSON response.
554 // If we are already nested inside a delayed write (rare: a serializer or handler calling c.JSON
555 // re-entrantly), allocate a fresh writer so the outer call's writer (which is &c.dsw) is not
556 // clobbered — reusing c.dsw here would make it reference itself.
557 if _, nested := resp.(*delayedStatusWriter); nested {
558 c.SetResponse(&delayedStatusWriter{ResponseWriter: resp, status: code})
559 } else {
560 c.dsw = delayedStatusWriter{ResponseWriter: resp, status: code}
561 c.SetResponse(&c.dsw)
562 }
563 defer c.SetResponse(resp)
564
565 return c.echo.JSONSerializer.Serialize(c, i, indent)
566}
567
568// JSON sends a JSON response with status code.
569func (c *Context) JSON(code int, i any) (err error) {

Callers 2

JSONMethod · 0.95
JSONPrettyMethod · 0.95

Calls 4

writeContentTypeMethod · 0.95
ResponseMethod · 0.95
SetResponseMethod · 0.95
SerializeMethod · 0.65

Tested by

no test coverage detected