Skip to main content

Response

Below are the different types of responses you can return to the user

Return JSON

func SomeHandler(c *core.Context) {
return c.Response.Json(myJson)
}

Return HTML

func SomeHandler(c *core.Context) {
return c.Response.HTML(myHTML)
}

Return Template

func SomeHandler(c *core.Context) {
return c.Response.Template("mytemplate.html", tmplData)
}

Return Text

func SomeHandler(c *core.Context) {
return c.Response.Text(myText)
}

Return Any response

func SomeHandler(c *core.Context) {
return c.Response.Any(anyResponse)
}

Set response headers

func SomeHandler(c *core.Context) {
return c.Response.SetHeader("key", "value").Json(myJson)
}

Set response content type

func SomeHandler(c *core.Context) {
return c.Response.SetContentType("application/json").Any(myJson)
}

Set response status code

func SomeHandler(c *core.Context) {
return c.Response.SetStatusCode(400).Json(myJson)
}

Redirect

func SomeHandler(c *core.Context) {
// 307 Temporary Redirect (preserves the HTTP method)
return c.Response.Redirect("/login")

// Use 303 See Other to switch to GET after a POST
return c.Response.Redirect("/users/list", true)
}

Force sending the response from a hook

Hooks can send a response early by calling ForceSendResponse. After that, the framework stops processing and sends the response to the user.

func Unauthorized(c *core.Context) {
c.Response.
SetStatusCode(401).
SetContentType("text/html").
HTML("<h1>unauthorized</h1>").
ForceSendResponse()
}

Download a file (buffer)

BufferFile sends the contents of a bytes.Buffer as a downloadable attachment:

func Download(c *core.Context) *core.Response {
var buf bytes.Buffer
buf.WriteString("file contents")

return c.Response.BufferFile("report.csv", "text/csv", buf)
}

Inline a file (buffer)

BufferInline is like BufferFile but the browser renders the content instead of downloading it:

func View(c *core.Context) *core.Response {
var buf bytes.Buffer
buf.WriteString("<h1>hello</h1>")

return c.Response.BufferInline("page.html", "text/html", buf)
}