]> git.cworth.org Git - rust-learning/commitdiff
Add dependencies on axum and tokio and implement a do-nothing server
authorCarl Worth <cworth@cworth.org>
Tue, 10 Mar 2026 05:20:10 +0000 (22:20 -0700)
committerCarl Worth <cworth@cworth.org>
Thu, 12 Mar 2026 04:14:58 +0000 (21:14 -0700)
This server binds to port 3000 on all interfaces and then just listens,
(with no routes configured to do anything).

The axum library gives us the server and router, (which, like I said,
we aren't using yet). And tokio gives us some network functionality
(see the TCP listener and the bind function) as well as some
asynchronous functionality, (see the #[tokio::main] attribute which
saves bunch of boilerplate that would otherwise be needed (creating a
tokio::runtime::Builder and giving it a function to run), and instead
lets us just use the entire body of main as the async function body
that tokio launches.

Cargo.toml
src/main.rs

index c2fd62edcac5188ad1b2198d0c38ed339299912a..8d2cc62f108ebf507fbd04102c172a1faa98ee9b 100644 (file)
@@ -4,5 +4,7 @@ version = "0.1.0"
 edition = "2024"
 
 [dependencies]
+axum = "0.8.8"
 serde = { version = "1", features = ["derive"]}
 serde_json = "1"
+tokio = { version = "1.50.0", features = ["full"] }
index 7154081ccc431f38a75bc9beda5b1867c834aa2e..baca8fea87c950cee7ba2387232eb6fc02d68ff8 100644 (file)
@@ -2,7 +2,8 @@ mod config;
 
 use std::error::Error;
 
-fn main() -> Result<(), Box<dyn Error>> {
+#[tokio::main]
+async fn main() -> Result<(), Box<dyn Error>> {
     let args: Vec<String> = std::env::args().collect();
     if args.len() < 2 {
         return Err(format!("Usage: {} <race-config.json>", args[0]).into());
@@ -16,5 +17,19 @@ fn main() -> Result<(), Box<dyn Error>> {
 
     eprintln!("Race: {}", config.name);
 
+    let bind = "0.0.0.0:3000";
+    eprintln!("Listening on {}", bind);
+
+    let listener = tokio::net::TcpListener::bind(&bind).await?;
+
+    let app = axum::Router::new();
+
+    axum::serve(listener, app)
+        .with_graceful_shutdown(async move {
+            tokio::signal::ctrl_c().await.ok();
+            eprintln!("\nShutting down.");
+        })
+        .await?;
+
     Ok(())
 }