Routing

HandlerFunc Routes

Use plain route handlers for small endpoints that do not need a controller.

By Guillermo Alvarez - Published Updated

Register a plain handler

Use HandleFunc when a route does not need controller state:

func Draw(router *lazyroutes.Scope) {
    router.HandleFunc("GET", "/health", func(
        w http.ResponseWriter,
        r *http.Request,
    ) error {
        w.WriteHeader(http.StatusNoContent)
        return nil
    })
}

The handler returns error, so it can still use the framework error path.

Keep small endpoints small

Plain handlers are useful for endpoints such as:

GET /health
GET /robots.txt
GET /up

Use a controller when the route needs shared controller helpers, automatic view rendering, format negotiation, or request-local render state.

Read route params

Plain handler routes use the same path syntax as controller routes:

router.HandleFunc("GET", "/files/{path...}", func(
    w http.ResponseWriter,
    r *http.Request,
) error {
    _, err := fmt.Fprintln(w, r.PathValue("path"))
    return err
})

Go's standard library extracts the path value. GoLazy still records route metadata for the request.

Return route errors

Expected HTTP failures can use controller-compatible errors:

return lazycontroller.Error(
    http.StatusNotFound,
    fmt.Errorf("file not found"),
)

That keeps error behavior consistent across controller and non-controller routes.