🧱Building response
Page description (optional)
Responses in indigo are built on the idea of builders. As a bonus, each method of the builder is chainable:
Of course, the recommended way to chain is to break each chained method onto a new line:
Alternatively, instead of the long and verbose request.Respond()...
, you can use shortcuts from http
package:
As a bonus, there's a shortcut for request.Respond()
directly: http.Respond
. And it can be used as a dummy handler, that always returns 200 OK (default response)
This will always give you 200 OK on main page
Full list of all the methods:
Code(status.Code) *http.Response
— set response code.Status(status.Status) *http.Response
— set response status text.ContentType(string) *http.Response
— set Content-Type value. May be used by the framework.TransferEncoding(string) *http.Response
— set Transfer-Encoding value. May be used by the framework.Header(key string, value ...string) *http.Response
— add a header to the response.Headers(map[string][]string) *http.Response
— add headers from the map.String(string) *http.Response
— set the body. Previous value will be replaced.Bytes([]byte) *http.Response
— same asString()
, but for byte slices.Write([]byte) (n int, err error)
— support ofio.Writer
interface.TryFile(path string) (*http.Response, error)
— try to send a file, and return an error in case of failure.File(path string) *http.Response
— chainable version of TryFile(). If an error occurred, it'll be sent instead of the actual file.Attachment(io.Reader, size int) *http.Response
— send arbitrary reader. If size is negative, it is considered unknown, thus chunked transfer encoding will be used.Cookie(cookies ...cookie.Cookie) *http.Response
— add a cookie to the response.TryJSON(any) (*http.Response, error)
— try to send a JSON data. It is being rendered in-place by built-in marshaller.JSON(any) *http.Response
— sends a JSON. If error occurred, it'll be set as the response's body.Error(error, ...status.Code) *http.Response
— in case error happened, return the response with the error set. If the error is an instance ofstatus.HTTPError
— the code will be set to the code from the error, otherwise 500 Internal Server Error is used. However, in case the error is not an instance ofstatus.HTTPError,
the error code can be overridden by setting it as the second argument. Please, note: if there's more than 1 error code specified, the rest will be ignored.Reveal() response.Fields
— returns a structure containing all the fields set.Clear() *http.Response
— clear all values set
Each request.Respond()
(and shortcuts to it) call clears the response builder. Calling it for a second time abolishes all values set before.
So in case you need to use the response builder as the io.Writer
object, you can't chain it:
Last updated