Routing

Middleware

Install request middleware and understand the GoLazy dispatch chain.

By Guillermo Alvarez - Published - Updated

Configure middleware

Applications install middleware through lazyapp.Config:

func App() *lazyapp.App {
    return lazyapp.New(lazyapp.Config{
        Name:   "sample_app",
        Drawer: Draw,
        Public: app.Public,
        Views:  app.Views,
        Middlewares: []lazydispatch.Middleware{
            requestIDMiddleware,
        },
    })
}

Middleware is request-wide behavior. Use it for concerns such as request IDs, origin checks, logging, or authentication gates.

Implement middleware

Middleware implements a small interface:

type Middleware interface {
    Handler(next http.Handler) http.Handler
}

For simple middleware, adapt a function:

var requestIDMiddleware = lazydispatch.MiddlewareFunc(
    func(next http.Handler) http.Handler {
        return http.HandlerFunc(func(
            w http.ResponseWriter,
            r *http.Request,
        ) {
            next.ServeHTTP(w, r)
        })
    },
)

This keeps GoLazy middleware close to ordinary standard-library handler composition.

Understand dispatch order

lazyapp.New builds the request chain in this order:

route-only response buffer and ETag handling
application middleware
router middleware
asset/public fallback middleware
404 final handler

Application middleware runs in the order listed. The request enters the first middleware first and the response unwinds in the opposite order.

Route before public assets

The router handles a request when a registered route owns the path. If no route owns the path, dispatch tries the public asset registry.

This lets application routes win over public files:

router.Get("/styles.css", debug.New, (*debug.Controller).Styles)

When that route exists, it handles /styles.css; otherwise the public file fallback can serve app/public/styles.css.

Use form method override

lazyapp installs route-scoped method override middleware for HTML forms. A form can submit POST with:

<input type="hidden" name="_method" value="patch">

The middleware accepts put, patch, and delete for routed form requests, then dispatches the request to the matching route. Cross-origin request rejection is separate; use lazydispatch/middlewares.CrossOriginProtection when the application needs that policy.