As mentioned in Chapter 1, Understanding HTTP, Go, and Echo, the primary purpose of a web application is to take in a request, and render a response to the caller. Fortunately for us, Echo has a multitude of ways we can render responses back to callers. The Echo Context has the following helpers that can be used to render responses, so that you as a developer will not need to serialize the response data yourself:
HTML(code int, html string) error HTMLBlob(code int, b []byte) error String(code int, s string) error JSON(code int, i interface{}) error JSONPretty(code int, i interface{}, indent string) error JSONBlob(code int, b []byte) error JSONP(code int, callback string, i interface{}) error JSONPBlob(code int, callback string, b []byte) error XML(code int, i interface{}) error XMLPretty(code int, i interface{}, indent string) error XMLBlob(code int, b []byte) error Blob(code int, contentType string, b []byte) error Stream(code int, contentType string, r io.Reader) error File(file string) error Attachment(file string, name string) error Inline(file string, name string) error NoContent(code int) error Redirect(code int, url string) error
Each of the preceding Context methods allow the developer to specify the particular content type encoding that is needed for the response of the web application. If your API is returning JSON, for example, you should use the Context.JSON method to render your structure to the caller.
How this works is very simple: when you call context.JSON, behind the scenes, Echo takes the first parameter code and writes that status code to the ResponseWriter. After the status and headers have been written, Echo then takes the interface{} structure that you pass as the second parameter, serializes said structure to JSON encoding, and then performs a ResponseWriter.Write with the resultant encoded JSON.
The following is an example from our $GOPATH/src/github.com/PacktPublishing/Echo-Essentials/chapter5/handlers/login.go code, where we return a JSON representation of the response structure:
return c.JSON(http.StatusOK, resp)
By calling the JSON method and specifying a response status code, and our renderings.LoginResponse structure as parameters, Echo will serialize our renderings.LoginResponse to JSON and write the response directly to the http.ResponseWriter, which means that the developer does not have to worry about encoding: