Quick Start: Hello, Warp!
This guide will walk you through creating your first warp
application. We'll build a simple web server that responds to requests with a personalized greeting.
1. Project Setup
First, create a new binary Rust project:
cargo new hello-warp
cd hello-warp
Next, add warp
and tokio
to your Cargo.toml
file:
[dependencies]
tokio = { version = "1", features = ["full"] }
warp = { version = "0.4", features = ["server"] }
2. Write the Code
Open src/main.rs
and replace its content with the following code:
// src/main.rs
use warp::Filter;
#[tokio::main]
async fn main() {
// Define a filter for the route: GET /hello/:name
// The path macro makes it easy to combine path segments and parameters.
let hello = warp::path!("hello" / String)
// The `map` function takes the extracted parameter and produces a reply.
.map(|name| format!("Hello, {}!", name));
println!("Server started at http://127.0.0.1:3030");
// Start the server, listening on the specified address.
warp::serve(hello)
.run(([127, 0, 0, 1], 3030))
.await;
}
Let's break down what's happening:
#[tokio::main]
: This macro sets up the Tokio async runtime.warp::path!("hello" / String)
: This is aFilter
that matches requests where:- The path starts with the segment
"hello"
. - The next path segment can be parsed as a
String
.
- The path starts with the segment
.map(|name| ...)
: This is a combinator that takes the value extracted by the previous filter (theString
from the path) and transforms it. Here, it creates a greetingString
.warp::serve(hello)
: This creates a server that will handle requests using thehello
filter..run(...)
: This binds the server to the address127.0.0.1:3030
and starts listening for incoming connections.
3. Run the Application
Now, run your application from the terminal:
cargo run
You should see the output: Server started at http://127.0.0.1:3030
.
4. Test It!
Open another terminal and use curl
to send a request to your new server:
curl http://127.0.0.1:3030/hello/warp
The server will respond with:
Hello, warp!
You can try different names in the URL:
curl http://127.0.0.1:3030/hello/Rust
# Expected output: Hello, Rust!
Congratulations, you've just built your first web service with warp
! From here, you can explore the Core Concepts to learn more about routing, data extraction, and error handling.