main.rs (1352B)
1 use actix_web::{App, HttpServer, Responder, get, rt::time::sleep, web}; 2 use std::{ 3 env, 4 sync::atomic::{AtomicUsize, Ordering}, 5 time::Duration, 6 }; 7 8 const EXPLANATION: &str = 9 "USAGE: 10 Delay server works by issuing an HTTP GET request in the format: 11 http://localhost:8080/[delay in ms]/[URL-encoded message] 12 13 If an argument is passed in when delayserver is started, that 14 argument will be used as the URL instead of 'localhost'. 15 16 Upon receiving a request, it immediately reports the following to the console: 17 18 {Message #} - {delay in ms}: {message} 19 20 The server then delays the response for the requested time and echoes the message back to the caller. 21 22 REQUESTS: 23 -------- 24 "; 25 26 static COUNTER: AtomicUsize = AtomicUsize::new(1); 27 28 #[get("/{delay}/{message}")] 29 async fn delay(path: web::Path<(u64, String)>) -> impl Responder { 30 let (delay_ms, message) = path.into_inner(); 31 let count = COUNTER.fetch_add(1, Ordering::SeqCst); 32 println!("#{count} - {delay_ms}ms: {message}"); 33 sleep(Duration::from_millis(delay_ms)).await; 34 message 35 } 36 37 #[actix_web::main] 38 async fn main() -> std::io::Result<()> { 39 let url = env::args() 40 .nth(1) 41 .unwrap_or_else(|| String::from("localhost")); 42 43 println!("{EXPLANATION}"); 44 HttpServer::new(|| App::new().service(delay)) 45 .bind((url, 8090))? 46 .run() 47 .await 48 }