Routing â
Mocket's routing system maps incoming HTTP requests to handler functions. It provides an Express.js-like API with optimized performance for both static and dynamic routes.
Basic Routing â
HTTP Methods â
Register routes using HTTP method functions:
moonbit
let app = @mocket.new(logger=mocket.new_production_logger())
app.get("/", _event => "GET request")
app.post("/users", _event => ({ "message": "User created" } : Json))
app.put("/users/:id", _event => "User updated")
app.delete("/users/:id", _event => "User deleted")Available methods: get, post, put, patch, delete, head, options, trace, connect
Catch-All Routes â
Use all() to handle any HTTP method:
moonbit
app.all("/api/*", _event => "API endpoint")Route Patterns â
Static Routes â
Static routes match exact paths:
moonbit
app.get("/about", handler)
app.get("/contact", handler)
app.get("/api/status", handler)Dynamic Routes â
Dynamic routes use parameters and wildcards:
Path Parameters â
Use :parameter to capture path segments:
moonbit
app.get("/users/:id", fn(event) {
let user_id = event.params["id"]
"User ID: " + user_id
})
app.get("/users/:id/posts/:post_id", event => {
let user_id = event.params.get("id").unwrap_or("unknown")
let post_id = event.params.get("post_id").unwrap_or("unknown")
({ "user_id": user_id, "post_id": post_id } : Json)
})Wildcards â
Use * to match any path segment:
moonbit
app.get("/files/*", event => {
let file_path = event.params.get("_").unwrap_or("")
"File path: " + file_path
})Route Matching â
Matching Priority â
Routes are matched in the order they are registered:
moonbit
app.get("/users/admin", _event => "Admin user") // This will match first
app.get("/users/:id", _event => "Regular user") // This won't match for /users/adminPerformance Characteristics â
Route Groups â
Group related routes with common prefixes:
moonbit
// API v1 routes
let api_v1 = mocket.group("/api/v1")
api_v1.get("/users", get_users_handler)
api_v1.post("/users", create_user_handler)
api_v1.get("/users/:id", get_user_handler)
// API v2 routes
let api_v2 = mocket.group("/api/v2")
api_v2.get("/users", get_users_v2_handler)
api_v2.post("/users", create_user_v2_handler)Advanced Patterns â
Optional Parameters â
moonbit
app.get("/posts/:id?", event => {
match event.params.get("id") {
Some(id) => "Post ID: " + id
None => "All posts"
}
})Multiple Parameters â
moonbit
app.get("/api/:version/users/:id/posts/:post_id", event => {
event.params
})