package main
import (
"fmt"
"log/slog"
"os"
"time"
"github.com/go-mizu/mizu"
)
// Example route that adds custom log entries
func home(c *mizu.Ctx) error {
c.Logger().Info("user visited home",
"method", c.Request().Method,
"path", c.Request().URL.Path,
"client_ip", c.ClientIP(),
)
return c.Text(200, "Home page")
}
// Simulate a slow route
func slow(c *mizu.Ctx) error {
start := time.Now()
time.Sleep(2 * time.Second)
elapsed := time.Since(start)
c.Logger().Info("slow request finished",
"path", c.Request().URL.Path,
"duration", elapsed.String(),
)
return c.Text(200, "Finished slow operation")
}
// Simulate an error and log the details
func fail(c *mizu.Ctx) error {
err := doSomething()
if err != nil {
c.Logger().Error("operation failed",
"error", err,
"user_agent", c.Request().UserAgent(),
"client_ip", c.ClientIP(),
)
return c.Text(500, "Something went wrong")
}
return c.Text(200, "Success")
}
func doSomething() error {
return fmt.Errorf("database connection lost")
}
func main() {
// Mizu logs in plain text by default.
// You can still attach your own structured logger if you want.
handler := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo})
logger := slog.New(handler)
app := mizu.New(
mizu.WithLogger(logger),
)
// Mizu automatically logs every request,
// so you do not need to add another logging middleware.
app.Get("/", home)
app.Get("/slow", slow)
app.Get("/fail", fail)
if err := app.Listen(":8080"); err != nil {
logger.Error("server failed", "error", err)
}
}