Skip to main content
In this lesson, you will learn how Mizu manages the lifecycle of an HTTP request. Every request in Mizu has its own context, which lets you handle timeouts, cancellations, and background operations safely. This helps you write clean, responsive handlers that stop when the client disconnects or when the server shuts down.

Code

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

import (
	"context"
	"log"
	"net/http"
	"time"

	"github.com/go-mizu/mizu"
)

// Slow handler that respects the request context
func slow(c *mizu.Ctx) error {
	ctx := c.Request().Context()

	select {
	case <-time.After(3 * time.Second):
		return c.Text(http.StatusOK, "Finished after 3 seconds")
	case <-ctx.Done():
		// Context canceled (client disconnected or timeout reached)
		return c.Text(499, "Request cancelled")
	}
}

// Fast handler that uses a manual timeout
func timed(c *mizu.Ctx) error {
	ctx, cancel := context.WithTimeout(c.Request().Context(), 2*time.Second)
	defer cancel()

	select {
	case <-time.After(1 * time.Second):
		return c.Text(http.StatusOK, "Completed within timeout")
	case <-ctx.Done():
		return c.Text(http.StatusGatewayTimeout, "Operation timed out")
	}
}

func main() {
	app := mizu.New()

	app.Get("/slow", slow)
	app.Get("/timed", timed)

	if err := app.Listen(":8080"); err != nil {
		log.Fatal(err)
	}
}

Run

Run the server with:
go run .
Then visit these URLs in your browser or use curl:
  • http://localhost:8080/slow Wait a few seconds to see the message ā€œFinished after 3 secondsā€. If you stop loading early, the handler detects it and stops.
  • http://localhost:8080/timed Returns quickly with ā€œCompleted within timeoutā€. If you increase the delay past 2 seconds, it will show ā€œOperation timed outā€.

How it works

Each request in Go includes a context.Context that ends when the request finishes. Mizu passes this context to your handlers automatically. You can use it to cancel work early, set timeouts, or handle cleanup when the request is done. In the /slow example, the handler simulates a long operation. If the user closes the browser or the server shuts down, the context is canceled and your code exits early. In /timed, you create your own timeout with context.WithTimeout, giving full control over how long the handler should run. This approach is important for tasks like database queries, API calls, or background jobs where you should stop safely when the request ends.

Try something new

Change the values inside time.After() or context.WithTimeout() to see how timeouts behave. You can also print ctx.Err() to understand why the context ended. Now you know how Mizu’s context system helps manage request lifecycles in a simple, predictable way. Next, continue to Query, Form, and Path to learn how to read data from incoming requests.