routing/
routing.rs

1//! Routing example for Axeon
2//!
3//! This example demonstrates different routing techniques including:
4//! - Basic routes
5//! - Path parameters
6//! - Query parameters
7//! - Different HTTP methods
8
9use axeon::{Response, Router, Server, ServerError};
10use serde::{Deserialize, Serialize};
11
12#[derive(Serialize, Deserialize)]
13struct User {
14    name: String,
15    role: String,
16}
17
18fn main() {
19    let mut app = Server::new();
20
21    // Basic GET route
22    app.get("/", |_req| async {
23        Response::text("Welcome to Axeon API server!")
24    });
25
26    // Route with path parameter
27    app.get("/users/:id", |req| async move {
28        let user_id = req.params.get("id").unwrap();
29        Response::text(format!("User ID: {}", user_id))
30    });
31
32    // POST request with JSON body
33    app.post("/users", |req| async move {
34        match req.body.json::<User>() {
35            Some(user) => Response::ok(&user),
36            None => Err(ServerError::BadRequest("Invalid JSON body".to_string())),
37        }
38    });
39
40    // Group routes under /api prefix
41    let mut api = Router::new();
42    api.get("/status", |_req| async {
43        Response::ok(&serde_json::json!({
44            "status": "operational",
45            "version": "1.0.0"
46        }))
47    });
48
49    // Mount the API router to the main server
50    app.mount("/api", api);
51
52    app.listen("127.0.0.1:3000")
53        .expect("Server failed to start")
54}