Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Import the core types we need from axum
- // use axum::{routing::get, Router};
- use axum::{
- routing::{get, post, put, delete},
- Router
- };
- use axum::extract::Path;
- mod webs;
- #[tokio::main]
- async fn main() {
- // Initialize tracing for request logging
- tracing_subscriber::fmt::init();
- // Build our router with a single route
- /*
- let app = Router::new()
- .route("/", get(webs::root_handler));
- */
- let app = build_router();
- // Create a TCP listener on port 3000
- let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
- .await
- .unwrap();
- println!("Server running on http://localhost:3000");
- // Start serving requests
- axum::serve(listener, app).await.unwrap();
- }
- // Build a router with RESTful routes for a users resource
- fn build_router() -> Router {
- Router::new()
- // Basic routes
- .route("/", get(index))
- .route("/users/{id}", get( get_user ) )
- // Nested path with multiple methods
- //.route("/users", get(list_users).post(create_user))
- // Path parameters use :param_name syntax
- //.route("/users/:id", get(get_user).put(update_user).delete(delete_user))
- // You can nest routers for better organization
- .nest("/api/v1", api_routes())
- }
- // Separate router for API routes - keeps main router clean
- fn api_routes() -> Router {
- Router::new()
- .route("/", get(webs::api_result).post(webs::api_result) )
- .route("/health", get(health_check))
- .route("/status", get(status))
- }
- // Handler functions are just async functions that return something
- // implementing IntoResponse
- // async fn root_handler_before() -> &'static str {
- // "Hello from Axum!"
- // }
- async fn index() -> &'static str {
- "API Root"
- }
- async fn health_check() -> &'static str {
- "Health OK"
- }
- async fn status() -> &'static str {
- "status: Running"
- }
- async fn get_user(Path(user_id): Path<u32>) -> String {
- format!("Fetching user with ID: {}", user_id)
- }
Advertisement
Add Comment
Please, Sign In to add comment