/users
, accepte un JSON contenant un nom d’utilisateur et renvoie une réponse simulée avec un identifiant calculé (longueur du nom) et un message de bienvenue.use std ::{ io , net :: SocketAddr };
use axum::{extract::Json, http::StatusCode, routing::post, Router}; use serde::{Deserialize, Serialize}; /// Structure representing the expected input JSON payload #[derive(Deserialize)] struct UserInput { username: String, } /// Structure representing the output JSON response #[derive(Serialize)] struct ApiResponse { user_id: u64, welcome: String, } /// Enum to represent possible top-level errors in main() #[derive(Debug)] enum MainError { TcpBind { source: io::Error }, // Binding to the TCP socket failed Serve { source: io::Error }, // Server run failed } #[tokio::main] async fn main() -> Result<(), MainError> { // Define the HTTP API routes let routes = Router::new().route("/users", post(handle_user)); // Bind a TCP socket on all interfaces at port 8000 let addr = SocketAddr::from(([0, 0, 0, 0], 8000)); let listener = tokio::net::TcpListener::bind(addr) .await .map_err(|source| MainError::TcpBind { source })?; // Start the HTTP server using the defined routes axum::serve(listener, routes.into_make_service()) .await .map_err(|source| MainError::Serve { source })} /// Handler for POST /users that processes JSON input and returns JSON output async fn handle_user(Json(input): Json<UserInput>) -> (StatusCode, Json<ApiResponse>) { // Simulate user creation: user_id based on username length let reply = ApiResponse { user_id: input.username.len() as u64, welcome: format!("Hello, {}!", input.username), }; // Return 201 Created with a JSON body (StatusCode::CREATED, Json(reply)) }