Skip to content

Responses ​

Added: v1.0.0

Zen provides response methods on *zen.Ctx for common content types. Methods that write a body set Content-Type automatically (except String).

Status ​

Writes the given HTTP status code with no body.

go
c.Status(http.StatusNoContent)

JSON ​

Sends a compact JSON response.

go
c.JSON(200, map[string]string{"status": "ok"})

JSONPretty ​

Sends an indented JSON response with two-space indentation.

go
c.JSONPretty(200, map[string]string{"status": "ok"})
// Response body:
// {
//   "status": "ok"
// }

XML ​

Sends an XML response.

go
c.XML(200, result)

HTML ​

Sends an HTML response with Content-Type: text/html; charset=utf-8.

go
c.HTML(200, "<h1>Hello</h1>")

String ​

Sends a plain text response. Does not set Content-Type.

go
c.String(200, "plain text")

Error ​

Sends a plain text error message (wraps http.Error). Sets Content-Type: text/plain; charset=utf-8.

go
c.Error(http.StatusBadRequest, "invalid email")

Redirect ​

Sends an HTTP redirect (wraps http.Redirect).

go
c.Redirect(http.StatusMovedPermanently, "https://example.com")

Stream ​

Streams data from an io.Reader with the given content type.

go
f, _ := os.Open("/tmp/video.mp4")
defer f.Close()
c.Stream(200, "video/mp4", f)

Blob ​

Sends a byte slice with the given content type.

go
c.Blob(200, "text/csv", data)

File ​

Serves a file. Content type is inferred automatically by http.ServeFile.

go
c.File("./public/index.html")

Attachment ​

Serves a file as a download with Content-Disposition: attachment.

go
c.Attachment("/tmp/report.pdf", "monthly-report.pdf")

Inline ​

Serves a file for inline display with Content-Disposition: inline.

go
c.Inline("/tmp/photo.jpg")

Template ​

Renders an HTML template from parsed templates. Load templates at startup from any fs.FS:

go
t := zen.LoadTemplates(os.DirFS("views"), "*.html")

r.GET("/", func(c *zen.Ctx) {
    c.Render(200, t, "index.html", map[string]any{
        "title": "Home",
        "user":  "Alice",
    })
})

Embed templates at compile time with embed.FS:

go
//go:embed views/*.html
var viewFS embed.FS

t := zen.LoadTemplates(viewFS, "*.html")

SSE ​

Sends a Server-Sent Event.

go
c.SSEvent("message", data)

Released under the MIT License.