Controllers

Redirects, Metadata, And Errors

Set response metadata, redirect safely, and return expected HTTP errors.

By Guillermo Alvarez - Published - Updated

Redirect after changes

Use controller redirects from actions:

func (c *PostsController) Create(
    _ http.ResponseWriter,
    _ *http.Request,
) error {
    post := c.posts.Create()
    return c.RedirectTo("/posts/"+post.Param, http.StatusSeeOther)
}

RedirectTo writes the redirect response and skips automatic rendering.

Redirect back safely

Use RedirectBackOrTo when a form should return to the referring page:

return c.RedirectBackOrTo("/posts", http.StatusSeeOther)

GoLazy only uses same-host referrers. External referrers fall back to the path you provide.

Set status and headers

Response metadata can be set before rendering:

c.Status(http.StatusCreated)
c.Header().Set("Cache-Control", "no-store")
c.Set("post", post)
return nil

Status does not commit the response early, so the normal template render can still run.

Return expected errors

Wrap expected failures with an HTTP status:

if !ok {
    return lazycontroller.Error(
        http.StatusNotFound,
        fmt.Errorf("post %q not found", postID),
    )
}

The framework error handler uses the status code and can render an error template or static error page when one is available.

Show detailed errors

When an application runs through lazy, the build uses the lazydev tag and unexpected errors are shown with detail. Production builds hide details unless the app opts in:

lazyapp.App{
    Config: lazyapp.Config{
        ForceDetailErrors: true,
    },
}

Unexpected errors are also logged to stderr so production responses can stay brief without losing the operational error.