GWibisono

main.rs part 2b

Feb 15th, 2026
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 2.04 KB | Source Code | 0 0
  1. // Import the core types we need from axum
  2. // use axum::{routing::get, Router};
  3. use axum::{
  4.     routing::{get, post, put, delete},
  5.     Router
  6. };
  7. use axum::extract::Path;
  8. mod webs;
  9.  
  10. #[tokio::main]
  11. async fn main() {
  12.     // Initialize tracing for request logging
  13.     tracing_subscriber::fmt::init();
  14.     // Build our router with a single route
  15. /*
  16.     let app = Router::new()
  17.         .route("/", get(webs::root_handler));
  18. */
  19.     let app = build_router();
  20.     // Create a TCP listener on port 3000
  21.     let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
  22.         .await
  23.         .unwrap();
  24.  
  25.     println!("Server running on http://localhost:3000");
  26.  
  27.     // Start serving requests
  28.     axum::serve(listener, app).await.unwrap();
  29. }
  30.  
  31. // Build a router with RESTful routes for a users resource
  32. fn build_router() -> Router {
  33.     Router::new()
  34.         // Basic routes
  35.         .route("/", get(index))
  36.         .route("/users/{id}", get( get_user ) )
  37.         // Nested path with multiple methods
  38.         //.route("/users", get(list_users).post(create_user))
  39.         // Path parameters use :param_name syntax
  40.         //.route("/users/:id", get(get_user).put(update_user).delete(delete_user))
  41.         // You can nest routers for better organization
  42.         .nest("/api/v1", api_routes())
  43. }
  44.  
  45. // Separate router for API routes - keeps main router clean
  46. fn api_routes() -> Router {
  47.     Router::new()
  48.         .route("/", get(webs::api_result).post(webs::api_result) )
  49.         .route("/health", get(health_check))
  50.         .route("/status", get(status))
  51. }
  52.  
  53. // Handler functions are just async functions that return something
  54. // implementing IntoResponse
  55. // async fn root_handler_before() -> &'static str {
  56. //     "Hello from Axum!"
  57.  
  58. // }
  59.  
  60.  
  61. async fn index() -> &'static str {
  62.    "API Root"
  63. }
  64.  
  65. async fn health_check() -> &'static str {
  66.     "Health OK"
  67. }
  68.  
  69. async fn status() -> &'static str {
  70.    "status: Running"
  71. }
  72.  
  73.  
  74. async fn get_user(Path(user_id): Path<u32>) -> String {
  75.    format!("Fetching user with ID: {}", user_id)
  76. }
Advertisement
Add Comment
Please, Sign In to add comment