1
0
mirror of https://github.com/labstack/echo.git synced 2024-12-22 20:06:21 +02:00
echo/website/content/guide/response.md
2015-10-02 12:04:15 -07:00

2.5 KiB

title menu
Response
main
parent weight
guide 60

Template

Context.Render(code int, name string, data interface{}) error

Renders a template with data and sends a text/html response with status code. Templates can be registered using Echo.SetRenderer(), allowing us to use any template engine.

Below is an example using Go html/template

  • Implement echo.Render interface
type Template struct {
    templates *template.Template
}

func (t *Template) Render(w io.Writer, name string, data interface{}) error {
	return t.templates.ExecuteTemplate(w, name, data)
}
  • Pre-compile templates

public/views/hello.html

{{define "hello"}}Hello, {{.}}!{{end}}
t := &Template{
    templates: template.Must(template.ParseGlob("public/views/*.html")),
}
  • Register templates
e := echo.New()
e.SetRenderer(t)
e.Get("/hello", Hello)
  • Render template
func Hello(c *echo.Context) error {
	return c.Render(http.StatusOK, "hello", "World")
}

JSON

Context.JSON(code int, v interface{}) error

Sends a JSON HTTP response with status code.

XML

Context.XML(code int, v interface{}) error

Sends an XML HTTP response with status code.

HTML

Context.HTML(code int, html string) error

Sends an HTML HTTP response with status code.

String

Context.String(code int, s string) error

Sends a text/plain HTTP response with status code.

File

Context.File(name string, attachment bool) error

File sends a response with the content of the file. If attachment is true, the client is prompted to save the file.

Static files

Echo.Static(path, root string) serves static files. For example, code below serves files from directory public/scripts for any request path starting with /scripts/.

e.Static("/scripts/", "public/scripts")

Serving a file

Echo.ServeFile(path, file string) serves a file. For example, code below serves file welcome.html for request path /welcome.

e.ServeFile("/welcome", "welcome.html")

Serving an index file

Echo.Index(file string) serves root index page - GET /. For example, code below serves root index page from file public/index.html.

e.Index("public/index.html")

Serving favicon

Echo.Favicon(file string) serves default favicon - GET /favicon.ico. For example, code below serves favicon from file public/favicon.ico.

e.Favicon("public/favicon.ico")