Skip to main content
In this lesson, you will learn what middleware is and how to use it in Mizu. Middleware is a function that runs before or after your main handler. It can log requests, check authentication, handle errors, or modify responses, all without changing your route logic. Mizu middleware follows Go’s net/http design, so you can use standard handlers or write your own in a simple, composable way.

Code

Create a file named main.go and add this code:

Run

Start your server:
Then open your browser and try these routes:

How it works

Middleware in Mizu is a function that takes a mizu.Handler and returns another mizu.Handler. Each middleware can decide whether to continue to the next handler or stop early. Every middleware gets the same *mizu.Ctx object and can read or modify the request and response. The next(c) call runs the next function in the chain.

Try something new

Add a timing middleware to measure how long each request takes:
Apply it to a specific route:
Middleware helps you keep your handlers clean while layering shared logic such as authentication, logging, metrics, and caching. Next, continue to Error Handling and Recover to learn how to handle panics and send friendly error messages.