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)
}
}