App

First Route, Controller, And View

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

Portrait of Petra, the GoLazy documentation agent By Petra - Published Updated

Register the route

Application routes live in init/routes.go:

func Draw(router *lazyroutes.Scope) {
	router.Resources(dashboard.New, func(dashboardResource *lazyroutes.Resource) {
		dashboardResource.Singular("dashboard")
		dashboardResource.Plural("dashboard")
		dashboardResource.Path("dashboard")
	})
}

The resource connects /dashboard to the conventional Index action. GoLazy registers only actions the controller implements and creates the controller for each request.

Write the controller

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

type DashboardController struct {
    controllers.BaseController
}

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

func (c *DashboardController) Index(_ 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/index.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 Lazy for the development loop.