HTTP响应
在echo的handlerFunc最后会返回一个数据用于到浏览器的渲染
返回String数据
Context.String(code int, s string) 用于发送一个带有状态码的纯文本响应。
func resp(c echo.Context) error { return c.String(http.StatusOK, "hello, Echo!") }
返回HTML数据
Context.HTML(code int, html string)
用于发送一个带状态码的简单 html 响应。如果你需要动态生成 html 内容需要使用模板
func resp(c echo.Context) error { return c.HTML(http.StatusOK, "<h1>Hello, Echo!</h1>") }
返回JSON数据
Context.JSON(code int, i interface{})
用于发送一个带状态码的 json 对象。它会将 golang 的对象转换成 json 字符串。
func resp(c echo.Context) error { u := User{ Name: "Eric Jin", Email: "123@gmail.com", } return c.JSON(http.StatusOK, u) }
JSON流
Context#JSON()
内部使用 json.Marshl
来转换 json 数据,对于大的数据来说性能不够好,这种情况下可以直接使用 json 流。
func resp(c echo.Context) error { u := User{ Name: "Eric Jin", Email: "123@gmail.com", } c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8) c.Response().WriteHeader(http.StatusOK) return json.NewEncoder(c.Response()).Encode(u) }返回
返回JSON Pretty
Context#JSONPretty(code int, i interface{}, indent string)
也是用于发送 json 数据。不过它打印出的 json 数据带有缩进(可以使用空格和 tab),更为好看。
func resp(c echo.Context) error { u := User{ Name: "Eric Jin", Email: "123@gmail.com", } return c.JSONPretty(http.StatusOK, u, " ") }
返回XML数据
Context#XML(code int, i interface{})
用来转换 golang 对象为 xml 数据发送响应。
type User struct { Name string `json:"name" xml:"name"` Email string `json:"email" xml:"email"` } func resp(c echo.Context) error { u := User{ Name: "Eric Jin", Email: "123@gmail.com", } return c.XML(http.StatusOK, u) }
Stream XML
类似于JSON流
func resp(c echo.Context) error { u := User{ Name: "Eric Jin", Email: "123@gmail.com", } c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationXMLCharsetUTF8) c.Response().WriteHeader(http.StatusOK) return xml.NewEncoder(c.Response()).Encode(u) }
XML Pretty
类似于JSONPretty
func resp(c echo.Context) error { u := User{ Name: "Eric Jin", Email: "123@gmail.com", } return c.XMLPretty(http.StatusOK, u, " ") }
发送文件
Context#File(file string)
用来发送一个文件为内容的响应。
func resp(c echo.Context) error { return c.File("desktop1.jpeg") }
发送附件
Context#Attachment(file, name string)
和发送文件的方法类似,只是它会多提供一个名称。
可以用于下载文件
func resp(c echo.Context) error { return c.Attachment("desktop1.jpeg", "test") }
发送流数据
Context#Stream(code int, contentType string, r io.Reader)
用来发送任意数据流响应。需要提供 content type,io.Reader 和状态码。
func resp(c echo.Context) error { f, err := os.Open("time.jpg") if err != nil { return err } return c.Stream(http.StatusOK, "image/png", f) }
发送空内容
func(c echo.Context) error { return c.NoContent(http.StatusOK) }
重定向
Context#Redirect(code int, url string)
,提供一个 url 用于重定向。
func(c echo.Context) error { return c.Redirect(http.StatusMovedPermanently, "/user") }