Controllers

Actions

Write controller action methods that render, redirect, stream, or write responses.

By Guillermo Alvarez - Published Updated

Use the standard signature

Most actions receive http.ResponseWriter and *http.Request and return an error:

func (c *PostsController) Index(
    _ http.ResponseWriter,
    _ *http.Request,
) error {
    c.Set("title", "Posts")
    c.Set("posts", c.posts.List())
    return nil
}

Returning nil lets GoLazy render the default view after the action returns.

Render a different view

Use Render when the action should select a different template:

func (c *PostsController) Preview(
    _ http.ResponseWriter,
    _ *http.Request,
) error {
    c.Set("title", "Preview")
    return c.Render("show")
}

Automatic rendering is skipped because the action rendered explicitly.

Write the response manually

Actions can write directly for non-template responses:

func (c *PostsController) Feed(w http.ResponseWriter, _ *http.Request) error {
    c.ContentType("text/plain; charset=utf-8")
    _, err := fmt.Fprintln(w, "posts")
    return err
}

If the action writes the response body, GoLazy does not need to render a view.

Return errors

Return expected HTTP failures with lazycontroller.Error:

return lazycontroller.Error(
    http.StatusNotFound,
    fmt.Errorf("post %q not found", postID),
)

Unexpected errors become 500 Internal Server Error.