Quick Start

First Route, Controller, And View

Wire one route to a controller action and render the matching template.

By Guillermo Alvarez - Published - Updated

Register the route

Application routes live in init/routes.go:

func Draw(router *lazyroutes.Scope) {
    router.Get("/dashboard", dashboard.New, (*dashboard.Controller).Show)
}

The route connects a method and path to a controller constructor and action. GoLazy creates the controller for each request.

Write the controller

The constructor receives application context. The action sets template data and returns nil:

type Controller struct {
    controllers.BaseController
}

func New(ctx context.Context) (*Controller, error) {
    base, err := controllers.NewBaseController(ctx)
    if err != nil {
        return nil, err
    }
    return &Controller{BaseController: base}, nil
}

func (c *Controller) Show(_ http.ResponseWriter, _ *http.Request) error {
    c.Set("title", "Dashboard")
    return nil
}

Returning nil lets GoLazy render the default view for the route action.

Add the view

The default template path is based on controller and action metadata:

app/views/dashboard/show.html.tpl

Use values set by the controller:

<h1>{{.title}}</h1>

The rendered view is supplied to the selected layout as .content.

Run it

Start the app:

lazy

Then open:

http://127.0.0.1:3000/dashboard

Use Run With lazy for the development loop.