Routing

Basic Routes

Register controller routes, path parameters, and route metadata with lazyroutes.

By Guillermo Alvarez - Published - Updated

Draw routes

Application routes live in init/routes.go:

func Draw(router *lazyroutes.Scope) {
    router.Get("/", home.New, (*home.HomeController).Index)
    router.Get("/posts/{post_id}", posts.New, (*posts.PostsController).Show)
}

Draw receives the framework-created *lazyroutes.Scope. It does not create the HTTP server, install public file fallback behavior, or return a handler.

Bind a controller action

Verb methods take a path, a controller constructor, and a method expression:

router.Post("/posts", posts.New, (*posts.PostsController).Create)
router.Patch("/posts/{post_id}", posts.New, (*posts.PostsController).Update)
router.Delete("/posts/{post_id}", posts.New, (*posts.PostsController).Delete)

The constructor receives only application context:

func New(ctx context.Context) (*PostsController, error)

The standard action signature receives the usual request values:

func (c *PostsController) Show(
    w http.ResponseWriter,
    r *http.Request,
) error {
    slug := r.PathValue("post_id")
    // Load data, set view values, and return nil.
    return nil
}

Use path syntax

GoLazy route paths use the standard library http.ServeMux pattern syntax:

/posts
/posts/{post_id}
/posts/{post_id}/comments/{comment_id}
/files/{path...}
/

Named segments are available through r.PathValue. GoLazy also records the names in route metadata so helpers can understand which values a path needs.

Inspect route metadata

The matched route is attached to the request context before the action runs:

route, params, ok := lazyroutes.RouteFromRequest(r)
if !ok {
    return fmt.Errorf("route metadata missing")
}

postID := params["post_id"]
c.Set("route", route.Name)
c.Set("postID", postID)
return nil

The metadata contains the route name, method, path, controller, action, namespace, and named parameter set.

Use the CLI when you need to inspect the app route map:

lazy routes

The command initializes the application with route-printing build tags and prints each route without starting the server.

Use HandlerFunc Routes for non-controller endpoints and REST Resources for conventional CRUD routes.