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.
c.Status(http.StatusNoContent)JSON
Sends a compact JSON response.
c.JSON(200, map[string]string{"status": "ok"})JSONPretty
Sends an indented JSON response with two-space indentation.
c.JSONPretty(200, map[string]string{"status": "ok"})
// Response body:
// {
// "status": "ok"
// }XML
Sends an XML response.
c.XML(200, result)HTML
Sends an HTML response with Content-Type: text/html; charset=utf-8.
c.HTML(200, "<h1>Hello</h1>")String
Sends a plain text response. Does not set Content-Type.
c.String(200, "plain text")Error
Sends a plain text error message (wraps http.Error). Sets Content-Type: text/plain; charset=utf-8.
c.Error(http.StatusBadRequest, "invalid email")Redirect
Sends an HTTP redirect (wraps http.Redirect).
c.Redirect(http.StatusMovedPermanently, "https://example.com")Stream
Streams data from an io.Reader with the given content type.
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.
c.Blob(200, "text/csv", data)File
Serves a file. Content type is inferred automatically by http.ServeFile.
c.File("./public/index.html")Attachment
Serves a file as a download with Content-Disposition: attachment.
c.Attachment("/tmp/report.pdf", "monthly-report.pdf")Inline
Serves a file for inline display with Content-Disposition: inline.
c.Inline("/tmp/photo.jpg")Template
Renders an HTML template from parsed templates. Load templates at startup from any fs.FS:
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:embed views/*.html
var viewFS embed.FS
t := zen.LoadTemplates(viewFS, "*.html")SSE
Sends a Server-Sent Event.
c.SSEvent("message", data)