### Basic warp Server Setup Source: https://github.com/seanmonstar/warp/blob/master/README.md A simple example demonstrating how to set up a basic warp server. This snippet defines a route for GET /hello/ and serves a personalized greeting. ```rust use warp::Filter; #[tokio::main] async fn main() { // GET /hello/warp => 200 OK with body "Hello, warp!" let hello = warp::path!("hello" / String) .map(|name| format!("Hello, {}!", name)); warp::serve(hello) .run(([127, 0, 0, 1], 3030)) .await; } ``` -------------------------------- ### Complete Warp Server Configuration Example Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/configuration.md A comprehensive example showing initialization of logging, CORS configuration, API route definition, combining routes, server address setup, and graceful shutdown. ```rust use warp::Filter; use http::Method; use std::net::SocketAddr; #[tokio::main] async fn main() { // Initialize logging env_logger::init_from_env( env_logger::Env::new().default_filter_or("info") ); // Configure CORS let cors = warp::cors() .allow_origin("https://example.com") .allow_methods(vec![Method::GET, Method::POST]) .allow_headers(vec![http::header::CONTENT_TYPE]) .max_age(3600) .build(); // API routes let api = warp::path("api") .and(warp::body::content_length_limit(1024 * 1024)) .and(warp::body::json::()) .map(|body| warp::reply::json(&body)); // Combine routes let routes = api .with(cors) .with(warp::log("myapp")); // Server configuration let addr: SocketAddr = "127.0.0.1:3030".parse().unwrap(); // Graceful shutdown let (tx, _) = tokio::sync::broadcast::channel(1); let shutdown = async { tokio::signal::ctrl_c().await.ok(); eprintln!("Shutdown signal received"); let _ = tx.send(()); }; // Run server println!("Server running on http://{{}}", addr); warp::serve(routes) .bind(addr) .await .graceful(shutdown) .run() .await; println!("Server stopped gracefully"); } ``` -------------------------------- ### Basic HTTP Server Quick Start Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/INDEX.md A minimal example demonstrating how to set up a basic HTTP server that responds to "/hello" with "Hello, World!". Requires tokio for async runtime. ```rust use warp::Filter; #[tokio::main] async fn main() { let hello = warp::path("hello") .map(|| "Hello, World!"); warp::serve(hello) .run(([127, 0, 0, 1], 3030)) .await; } ``` ```toml [dependencies] warp = { version = "0.4", features = ["server"] } tokio = { version = "1", features = ["full"] } ``` -------------------------------- ### Basic HTTP Server Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/INDEX.md Demonstrates setting up a basic HTTP server using Warp's Filter abstraction. This example serves a "Hello, World!" response for GET requests to the "/hello" path. ```rust use warp::Filter; #[tokio::main] async fn main() { let route = warp::get() .and(warp::path("hello")) .map(|| "Hello, World!"); warp::serve(route) .run(([127, 0, 0, 1], 3030)) .await; } ``` -------------------------------- ### Basic HTTP Server Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/api-reference/serve-and-server.md Sets up a simple HTTP server that responds to a specific path parameter. This is a fundamental example for starting with Warp. ```rust use warp::Filter; #[tokio::main] async fn main() { let hello = warp::path("hello") .and(warp::path::param::()) .map(|name: String| format!("Hello, {}!", name)); warp::serve(hello) .run(([127, 0, 0, 1], 3030)) .await; } // GET /hello/warp -> "Hello, warp!" ``` -------------------------------- ### Basic Tracing Setup Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/configuration.md Applies tracing to routes with a specified service name. Requires `tracing` subscriber setup. ```rust let routes = filter .with(warp::trace("service_name")); ``` -------------------------------- ### RESTful API Example Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/INDEX.md Illustrates building a RESTful API with Warp, handling GET and POST requests for managing "items". It includes JSON serialization/deserialization and status code handling. ```rust use warp::Filter; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize)] struct Item { id: u64, name: String } #[tokio::main] async fn main() { let list = warp::get() .and(warp::path("items")) .and(warp::path::end()) .map(|| warp::reply::json(&vec![Item { id: 1, name: "Item 1".into() }])); let get = warp::get() .and(warp::path!("items" / u64)) .map(|id: u64| warp::reply::json(&Item { id, name: format!("Item {}", id) })); let create = warp::post() .and(warp::path("items")) .and(warp::body::json::()) .map(|item: Item| warp::reply::with_status( warp::reply::json(&item), warp::http::StatusCode::CREATED )); let routes = list.or(get).or(create); warp::serve(routes) .run(([127, 0, 0, 1], 3030)) .await; } ``` -------------------------------- ### RESTful JSON API Example Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/api-reference/reply-and-responses.md An example demonstrating how to build a RESTful JSON API using Warp, including GET and POST operations for items. ```APIDOC ## Composite Examples ### RESTful JSON API ```rust use serde::{Deserialize, Serialize}; use warp::{Filter, reply::Reply, http::StatusCode}; #[derive(Serialize)] struct Item { id: u64, name: String, price: f64, } #[derive(Deserialize)] struct CreateItem { name: String, price: f64, } #[derive(Serialize)] struct ErrorResponse { error: String, } // GET /items/:id let get_item = warp::get() .and(warp::path!("items" / u64)) .map(|id: u64| { let item = Item { id, name: "Widget".to_string(), price: 9.99, }; warp::reply::json(&item) }); // POST /items let create_item = warp::post() .and(warp::path("items")) .and(warp::body::json::()) .map(|item: CreateItem| { let created = Item { id: 123, name: item.name, price: item.price, }; warp::reply::with_status( warp::reply::json(&created), StatusCode::CREATED ) }); let routes = get_item.or(create_item); ``` ``` -------------------------------- ### Run Hello World Example Source: https://github.com/seanmonstar/warp/blob/master/examples/README.md Demonstrates how to run the basic "hello world" Warp service using Cargo. ```bash > cargo run --example hello ``` -------------------------------- ### Warp Path Macro Example - Get User Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/api-reference/filters-method-and-path.md An example demonstrating how to use the `path!` macro with `warp::get()` to define a route that captures a user ID from the path. ```rust use warp::Filter; // GET /api/users/123 let get_user = warp::get() .and(warp::path!("api" / "users" / u64)) .map(|id: u64| format!("User {}", id)); ``` -------------------------------- ### Full-Featured API Example Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/api-reference/filters-advanced.md This example demonstrates building a complete Warp API with CORS configuration, multiple routes for API data and POST submissions, static file serving, and logging. It uses `tokio::main` for asynchronous execution. ```rust use warp::Filter; #[tokio::main] async fn main() { // Configure CORS let cors = warp::cors() .allow_any_origin() .allow_methods(vec![http::Method::GET, http::Method::POST]) .allow_headers(vec![http::header::CONTENT_TYPE]); // API routes let api = warp::path("api") .and( warp::get() .and(warp::path("data")) .map(|| warp::reply::json(&vec![1, 2, 3])) .or( warp::post() .and(warp::path("submit")) .and(warp::body::json()) .map(|body: serde_json::Value| { warp::reply::json(&body) }) ) ); // Static files let static_files = warp::path("static") .and(warp::fs::dir("public")); // Combine routes with middleware let routes = api .or(static_files) .with(cors) .with(warp::log("myapp")); warp::serve(routes) .run(([127, 0, 0, 1], 3030)) .await; } ``` -------------------------------- ### RESTful JSON API with GET and POST Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/api-reference/reply-and-responses.md This example demonstrates building a RESTful API using warp filters for GET and POST requests. It handles JSON serialization and deserialization for requests and responses, including setting a CREATED status for POST. ```rust use serde::{Deserialize, Serialize}; use warp::{Filter, reply::Reply, http::StatusCode}; #[derive(Serialize)] struct Item { id: u64, name: String, price: f64, } #[derive(Deserialize)] struct CreateItem { name: String, price: f64, } #[derive(Serialize)] struct ErrorResponse { error: String, } // GET /items/:id let get_item = warp::get() .and(warp::path!("items" / u64)) .map(|id: u64| { let item = Item { id, name: "Widget".to_string(), price: 9.99, }; warp::reply::json(&item) }); // POST /items let create_item = warp::post() .and(warp::path("items")) .and(warp::body::json::()) .map(|item: CreateItem| { let created = Item { id: 123, name: item.name, price: item.price, }; warp::reply::with_status( warp::reply::json(&created), StatusCode::CREATED ) }); let routes = get_item.or(create_item); ``` -------------------------------- ### Response Creation Example Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/types.md An example showing how to construct an HTTP response with a status code and body using warp's http::Response builder. ```rust let response = warp::http::Response::builder() .status(200) .body("Hello".into()) .unwrap(); ``` -------------------------------- ### Server Setup and Execution Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/README.md Documentation for setting up and running a warp server. Covers server creation, binding to addresses, handling incoming connections, and graceful shutdown. ```APIDOC ## Server Setup and Execution ### Description This section provides guidance on configuring and launching a warp web server, including methods for binding to network interfaces and managing the server's lifecycle. ### Server Creation - `serve(service: S)`: Creates a server with the given service. ### Server Methods - `run(addr: Addr)`: Runs the server on the specified address. - `bind(addr: Addr)`: Binds the server to an address, returning a future. - `incoming(listener: L)`: Creates a server from an incoming connection listener. - `graceful(listener: L)`: Runs the server with graceful shutdown support. ### Service Function - `service(f: F)`: Creates a service from a function. ``` -------------------------------- ### Warp Path Macro Example - Get Comment Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/api-reference/filters-method-and-path.md This example shows the `path!` macro used with `warp::get()` to capture multiple parameters, specifically a post ID and a comment ID, from the URL. ```rust use warp::Filter; // GET /posts/42/comments/7 let get_comment = warp::get() .and(warp::path!("posts" / u64 / "comments" / u64)) .map(|post_id: u64, comment_id: u64| { format!("Post {} Comment {}", post_id, comment_id) }); ``` -------------------------------- ### Test a Warp Route with warp::test Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/configuration.md This example demonstrates how to use the `warp::test` module to simulate a GET request to a simple route and assert the response status and body. ```rust #[tokio::test] async fn test_get_endpoint() { let route = warp::path("hello") .map(|| "Hello, World!"); let res = warp::test::request() .method("GET") .path("/hello") .reply(&route) .await; assert_eq!(res.status(), 200); assert_eq!(res.body(), "Hello, World!"); } ``` -------------------------------- ### BoxedFilter Usage Example Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/types.md An example showing how to use `boxed()` to create a `BoxedFilter`. This is particularly helpful when you need to return a filter without exposing its complex generic type signature. ```rust fn my_filter() -> warp::filters::BoxedFilter<(impl warp::Reply,)> { warp::any() .map(|| "response") .boxed() } ``` -------------------------------- ### Custom Reject Implementation Example Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/types.md An example demonstrating how to define and implement a custom rejection type by deriving Debug and implementing the Reject trait. ```rust #[derive(Debug)] struct InvalidToken; impl warp::reject::Reject for InvalidToken {} ``` -------------------------------- ### BoxedFilter Constructor Example Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/types.md An example demonstrating the creation of a BoxedFilter using the `new` method. This is useful for returning filters with complex generic types without explicit naming. ```rust pub fn new(filter: F) -> Self where F: Filter + Send + Sync + 'static, F::Error: Into, { ``` -------------------------------- ### serve() Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/api-reference/serve-and-server.md Creates a Server configured to handle requests with the given filter. This is the primary function to start a Warp server. ```APIDOC ## serve() ### Description Creates a Server configured to handle requests with the given filter. ### Function Signature ```rust pub fn serve(filter: F) -> Server where F: Filter + Clone + Send + Sync + 'static, F::Extract: Reply, F::Error: IsReject, ``` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Type Parameters * **F**: `Filter + Clone + Send + Sync + 'static` - Request filter ### Returns * `Server` - a configured server ready to bind/run ### Example ```rust use warp::Filter; #[tokio::main] async fn main() { let hello = warp::path("hello") .map(|| "Hello, World!"); warp::serve(hello) .run(([127, 0, 0, 1], 3030)) .await; } ``` ``` -------------------------------- ### Full WebSocket Chat Application Source: https://github.com/seanmonstar/warp/blob/master/examples/README.md A complete WebSocket application example demonstrating a chat server using Warp. ```rust use std::collections::HashMap; use std::sync::{Arc, Mutex}; use warp::Filter; use warp::ws::{Message, WebSocket}; use futures_util::{StreamExt, SinkExt}; type Clients = Arc>>; #[tokio::main] async fn main() { let clients = Clients::default(); let chat = warp::path("chat") .and(warp::ws()) .and(with_clients(clients.clone())) .map(|ws: warp::ws::Ws, clients: Clients| { ws.on_upgrade(move |websocket| async move { handle_websocket(websocket, clients).await; }) }); warp::serve(chat).run(([127, 0, 0, 1], 3030)).await; } fn with_clients(clients: Clients) -> impl Filter { warp::any().map(move || clients.clone()) } async fn handle_websocket(websocket: WebSocket, clients: Clients) { let (tx, mut rx) = websocket.split(); let mut user_id = 0; // Assign a unique ID to the user (simplified) { let mut clients_map = clients.lock().unwrap(); user_id = clients_map.len() + 1; clients_map.insert(user_id, tx); } while let Some(message) = rx.next().await { if let Ok(msg) = message { if msg.is_text() { let text = msg.to_str().unwrap(); let mut clients_map = clients.lock().unwrap(); for (&id, sender) in clients_map.iter_mut() { if id != user_id { if sender.send(Message::text(format!("{}: {}", user_id, text))).await.is_err() { // Handle send error, maybe remove client } } } } } } // Remove user when disconnected clients.lock().unwrap().remove(&user_id); } ``` -------------------------------- ### Full SSE Chat Application Source: https://github.com/seanmonstar/warp/blob/master/examples/README.md A complete Server-Sent Events application example demonstrating a chat server using Warp. ```rust use warp::Filter; use futures_util::{Stream, stream, StreamExt, SinkExt}; use std::sync::{Arc, Mutex}; use std::collections::HashMap; // Simplified SSE sender struct SseSender(warp::ws::WsSender); impl SseSender { fn send(&mut self, data: String) -> Result<(), warp::Error> { self.0.send(Message::text(data)).compat().await } } // Simplified client management type Clients = Arc>>; #[tokio::main] async fn main() { let clients = Clients::default(); let chat = warp::path("chat") .and(warp::get()) .and(with_clients(clients.clone())) .and_then(|clients: Clients| async move { let mut id = 0; // Assign a unique ID (simplified) { let mut clients_map = clients.lock().unwrap(); id = clients_map.len() + 1; clients_map.insert(id, SseSender(warp::ws::WsSender::new())); // Placeholder, needs proper WebSocket upgrade } let stream = stream::iter( (0..10).map(|i| Ok(format!("data: Message {} from client {}\n\n", i, id))) ); Ok(warp::sse::reply(stream)) }); warp::serve(chat).run(([127, 0, 0, 1], 3030)).await; } fn with_clients(clients: Clients) -> impl Filter { warp::any().map(move || clients.clone()) } ``` -------------------------------- ### Error Response Example Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/api-reference/reply-and-responses.md An example demonstrating how to handle and return custom error responses in Warp. ```APIDOC ### Error Response ```rust use warp::{Filter, reject::Reject, Rejection, reply::Reply, http::StatusCode}; use serde::Serialize; #[derive(Serialize)] struct ErrorReply { error: String, code: u16, } #[derive(Debug)] struct NotFound; impl Reject for NotFound {} async fn handle_rejection(err: Rejection) -> Result { if let Some(_) = err.find::() { return Ok(warp::reply::with_status( warp::reply::json(&ErrorReply { error: "Not found".to_string(), code: 404, }), StatusCode::NOT_FOUND, )); } Ok(warp::reply::with_status( warp::reply::json(&ErrorReply { error: "Internal server error".to_string(), code: 500, }), StatusCode::INTERNAL_SERVER_ERROR, )) } let route = warp::any() .recover(handle_rejection); ``` ``` -------------------------------- ### Address Binding Examples Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/api-reference/serve-and-server.md Demonstrates various ways to bind a Warp server to different network addresses, including IPv4 loopback, all interfaces, IPv6 loopback, and using `std::net::SocketAddr`. ```rust // IPv4 loopback warp::serve(route).run(([127, 0, 0, 1], 3030)).await; // IPv4 all interfaces warp::serve(route).run(([0, 0, 0, 0], 3030)).await; // IPv6 loopback warp::serve(route).run(([0, 0, 0, 0, 0, 0, 0, 1], 3030)).await; // Using std::net::SocketAddr use std::net::SocketAddr; let addr: SocketAddr = "127.0.0.1:3030".parse().unwrap(); warp::serve(route).run(addr).await; ``` -------------------------------- ### Using Custom HTTP Methods Source: https://github.com/seanmonstar/warp/blob/master/examples/README.md Demonstrates how to handle custom HTTP methods beyond the standard GET, POST, PUT, DELETE in Warp. ```rust use warp::Filter; #[tokio::main] async fn main() { // Define a filter for a custom method, e.g., 'CUSTOM' let custom_method_filter = warp::method().and(warp::method::custom(warp::http::Method::from_bytes(b"CUSTOM").unwrap())); let custom_route = custom_method_filter .and(warp::path("custom")) .map(|| "Handled custom method!"); warp::serve(custom_route).run(([127, 0, 0, 1], 3030)).await; } ``` -------------------------------- ### Warp CORS Configuration Example Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/errors.md Configures CORS with allowed origins, methods, and headers. Demonstrates a scenario that would trigger CorsForbidden if validation fails. ```rust use warp::Filter; let cors = warp::cors() .allow_origin("https://example.com") .allow_methods(vec![http::Method::GET]) .build(); // CORS preflight from https://other.com with POST -> CorsForbidden ``` -------------------------------- ### Environment Variables for Logging Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/configuration.md Examples of setting environment variables to control logging levels for cargo run commands. ```bash RUST_LOG=debug cargo run ``` ```bash RUST_LOG=warp=trace cargo run ``` ```bash RUST_LOG=warp::filters=info cargo run ``` -------------------------------- ### Example: Triggering MissingExtension Rejection Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/errors.md This example demonstrates how a route using `warp::ext::get::()` will result in a 500 Internal Server Error if the `UserId` extension has not been inserted into the request. ```rust use warp::Filter; #[derive(Clone)] struct UserId(u64); // This will reject with 500 if UserId not inserted let route = warp::ext::get::(); ``` -------------------------------- ### Multi-Route API with JSON Handling Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/api-reference/serve-and-server.md Constructs a RESTful API with multiple routes for listing, retrieving, and creating users. It uses `serde` for JSON serialization and deserialization and handles different HTTP methods (GET, POST). ```rust use warp::Filter; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize)] struct User { id: u64, name: String, } #[tokio::main] async fn main() { // GET /users let list_users = warp::get() .and(warp::path("users")) .and(warp::path::end()) .map(|| { warp::reply::json(&vec![ User { id: 1, name: "Alice".to_string() }, User { id: 2, name: "Bob".to_string() }, ]) }); // GET /users/:id let get_user = warp::get() .and(warp::path!("users" / u64)) .and(warp::path::end()) .map(|id: u64| { warp::reply::json(&User { id, name: format!("User {}", id), }) }); // POST /users let create_user = warp::post() .and(warp::path("users")) .and(warp::path::end()) .and(warp::body::json::()) .map(|user: User| { warp::reply::with_status( warp::reply::json(&user), warp::http::StatusCode::CREATED, ) }); let routes = list_users .or(get_user) .or(create_user); warp::serve(routes) .run(([127, 0, 0, 1], 3030)) .await; } ``` -------------------------------- ### Environment Variable for Tracing Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/configuration.md Example of setting the RUST_LOG environment variable to control tracing levels for a specific application name. ```bash RUST_LOG=myapp=debug cargo run ``` -------------------------------- ### Handling Missing Header in Warp Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/errors.md This example shows how to handle a 400 Bad Request error when a required header is missing. It attempts to retrieve the 'x-api-key' header as a String. ```rust use warp::Filter; let route = warp::header::("x-api-key"); // Request without x-api-key header -> 400 Bad Request ``` -------------------------------- ### HTTP Routing Filters Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/README.md Documentation for filters related to HTTP routing, including method and path filtering. This covers methods like `get()`, `post()`, `path()`, and the `path!` macro. ```APIDOC ## HTTP Routing Filters ### Description This section describes filters used for defining routes based on HTTP methods and URL paths. It enables precise control over which requests are handled by specific filter chains. ### Method Filters - `get()`: Matches GET requests. - `post()`: Matches POST requests. - `put()`: Matches PUT requests. - `delete()`: Matches DELETE requests. - `head()`: Matches HEAD requests. - `options()`: Matches OPTIONS requests. - `patch()`: Matches PATCH requests. - `method(method: Method)`: Matches requests with a specific HTTP method. ### Path Filters - `path(segment: S)`: Matches a specific path segment. - `param(name: N)`: Extracts a path parameter. - `end()`: Matches the end of the path. - `path!(...)`: Macro for defining complex path structures. ``` -------------------------------- ### Define RESTful API Routes with Warp Filters Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/api-reference/filters-method-and-path.md This snippet demonstrates how to define various HTTP methods (GET, POST, PUT, DELETE) and path parameters for a RESTful API using Warp filters. It shows how to match specific paths like /users and /users/:id. ```Rust use warp::Filter; let users = warp::path("users"); // GET /users let list = warp::get() .and(users.clone()) .and(warp::path::end()) .map(|| "List users"); // GET /users/:id let get = warp::get() .and(users.clone()) .and(warp::path::param::()) .and(warp::path::end()) .map(|id: u64| format!("Get user {}", id)); // POST /users let create = warp::post() .and(users.clone()) .and(warp::path::end()) .map(|| "Create user"); // PUT /users/:id let update = warp::put() .and(users.clone()) .and(warp::path::param::()) .and(warp::path::end()) .map(|id: u64| format!("Update user {}", id)); // DELETE /users/:id let delete = warp::delete() .and(users.clone()) .and(warp::path::param::()) .and(warp::path::end()) .map(|id: u64| format!("Delete user {}", id)); let routes = list .or(get) .or(create) .or(update) .or(delete); ``` -------------------------------- ### Handle WebSocket Connections in Warp Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/INDEX.md Set up a Warp route to handle WebSocket connections using the `warp::ws()` filter. This example shows the basic structure for accepting and potentially handling WebSocket messages. ```rust use warp::Filter; #[tokio::main] async fn main() { let chat = warp::path("ws") .and(warp::ws()) .map(|ws: warp::ws::WebSocket| { // Handle WebSocket connection }); warp::serve(chat) .run(([127, 0, 0, 1], 3030)) .await; } ``` -------------------------------- ### Handling Unsupported Media Type in Warp Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/errors.md This example shows how to handle a 415 Unsupported Media Type error when the request's Content-Type header does not match the expected type for body parsing. It attempts to parse the body as JSON. ```rust use warp::Filter; let route = warp::body::json::(); // POST with Content-Type: text/plain -> 415 Unsupported Media Type // POST with Content-Type: application/json -> OK ``` -------------------------------- ### Create and Run a Warp Server Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/api-reference/serve-and-server.md Demonstrates the basic usage of `warp::serve` to create a server with a simple filter and run it on a specified address. ```rust use warp::Filter; #[tokio::main] async fn main() { let hello = warp::path("hello") .map(|| "Hello, World!"); warp::serve(hello) .run(([127, 0, 0, 1], 3030)) .await; } ``` -------------------------------- ### Run Warp Server with a Basic Route Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/api-reference/serve-and-server.md Shows how to create a Warp server that responds with a simple reply for any request and runs it. ```rust use warp::Filter; #[tokio::main] async fn main() { let route = warp::any().map(warp::reply); warp::serve(route) .run(([127, 0, 0, 1], 3030)) .await; } ``` -------------------------------- ### Initialize Tracing Subscriber and Serve Routes Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/configuration.md Demonstrates initializing the tracing subscriber and serving routes with tracing enabled. ```rust use tracing_subscriber; #[tokio::main] async fn main() { tracing_subscriber::fmt::init(); let routes = warp::any() .with(warp::trace("myapp")); warp::serve(routes) .run(([127, 0, 0, 1], 3030)) .await; } ``` -------------------------------- ### Configure Warp Server with Custom Listener Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/api-reference/serve-and-server.md Demonstrates using a custom `TcpListener` with `warp::serve` and then running the server. ```rust use warp::Filter; use tokio::net::TcpListener; #[tokio::main] async fn main() { let route = warp::any().map(warp::reply); let listener = TcpListener::bind(([127, 0, 0, 1], 3030)) .await .expect("failed to bind"); warp::serve(route) .incoming(listener) .run() .await; } ``` -------------------------------- ### Basic Hello World API Source: https://github.com/seanmonstar/warp/blob/master/examples/README.md A simple "Hello World" API implemented with Warp. ```rust use warp::Filter; #[tokio::main] async fn main() { // GET / -> 200 OK with body "Hello, World!" let hello = warp::path!("hello").map(|| "Hello, World!"); warp::serve(hello).run(([127, 0, 0, 1], 3030)).await; } ``` -------------------------------- ### Serving Static Files Source: https://github.com/seanmonstar/warp/blob/master/examples/README.md Demonstrates how to serve static files from a directory using Warp. ```rust use warp::Filter; #[tokio::main] async fn main() { let files = warp::fs::dir("static/"); warp::serve(files).run(([127, 0, 0, 1], 3030)).await; } ``` -------------------------------- ### Warp GET Method Filter Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/api-reference/filters-method-and-path.md Use this filter to require that an incoming request uses the GET HTTP method. Non-GET requests are rejected with a 405 Method Not Allowed error. ```rust use warp::Filter; let get_only = warp::get() .map(|| "GET request received"); ``` -------------------------------- ### File Structure and Methods Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/types.md Represents a file for serving. Automatically serves with the correct MIME type. The `path()` method retrieves the file's path. ```rust pub struct File { // ... internal ... } impl Reply for File impl File { pub fn path(&self) -> &Path } ``` -------------------------------- ### Serving a Directory of Files Source: https://github.com/seanmonstar/warp/blob/master/examples/README.md Shows how to serve an entire directory of static files using Warp. ```rust use warp::Filter; #[tokio::main] async fn main() { let dir = warp::fs::dir("public/"); warp::serve(dir).run(([127, 0, 0, 1], 3030)).await; } ``` -------------------------------- ### Bind and Run a Warp Server Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/api-reference/serve-and-server.md Illustrates binding a Warp server to an address, returning an active listener, and then running it. ```rust use warp::Filter; #[tokio::main] async fn main() { let route = warp::any().map(warp::reply); let server = warp::serve(route) .bind(([127, 0, 0, 1], 3030)) .await; // Now can call .run() or .graceful() server.run().await; } ``` -------------------------------- ### get() Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/api-reference/filters-headers-and-extraction.md Extracts a value of type T from request extensions. Rejects with a 500 Internal Server Error if the extension is not found. ```APIDOC ## get() ### Description Extracts a value from request extensions. ### Type Parameters | Parameter | Constraint | |-----------|-----------| | `T` | `Clone + Send + Sync + 'static` - Type stored in extensions | ### Returns Filter extracting `(T,)` - cloned extension value. ### Rejects with: - 500 Internal Server Error: Extension not found ### Example: ```rust use warp::Filter; #[derive(Clone)] struct UserId(u64); let route = warp::any() .and(warp::ext::get::()) .map(|user_id: UserId| { format!("User ID: {}", user_id.0) }); ``` ``` -------------------------------- ### Method Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/types.md An enum representing standard HTTP methods such as GET, POST, PUT, DELETE, etc. It can also include custom methods. ```APIDOC ## Method ### Description An enum representing standard HTTP methods such as GET, POST, PUT, DELETE, etc. It can also include custom methods. ### Extracted by `warp::method()` ``` -------------------------------- ### Warp Path Macro - With Parameters Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/api-reference/filters-method-and-path.md Shows how to use the `path!` macro to include path parameters of various types, such as `u64`. ```rust use warp::Filter; // With parameters warp::path!("users" / u64) warp::path!("posts" / u64 / "comments" / u64) ``` -------------------------------- ### Warp Method Filter Example Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/api-reference/filters-method-and-path.md This filter extracts the HTTP method of a request without performing any filtering. It's useful for inspecting the method or for conditional logic based on the method. ```rust use warp::Filter; let route = warp::method() .map(|m: http::Method| { format!("Method: {}", m) }); ``` -------------------------------- ### Build CORS Filter with Multiple Origins and Methods Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/configuration.md Constructs a CORS filter that allows requests from specific origins and permits GET and POST methods. Credentials are also allowed. ```rust let cors = warp::cors() .allow_origin("https://example.com") .allow_origin("https://app.example.com") .allow_methods(vec![Method::GET, Method::POST]) .allow_headers(vec![http::header::CONTENT_TYPE]) .allow_credentials(true) .build(); ``` -------------------------------- ### Implement a Dynamic Redirect Based on Conditions Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/api-reference/multipart-and-specialized.md Conditionally redirect users, for example, to a login page if an authorization header is missing. The `warp::redirect()` function is used within an `and_then` block. ```rust use warp::Filter; let redirect_to_login = warp::path("admin") .and(warp::header::optional::("authorization")) .and_then(|auth: Option| async move { if auth.is_none() { Ok(warp::redirect(warp::http::Uri::from_static("/login"))) } else { Err::<_, warp::Rejection>(warp::reject::reject()) } }); ``` -------------------------------- ### reply() Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/api-reference/reply-and-responses.md Creates an empty HTTP 200 OK response with an empty body. ```APIDOC ## reply() ### Description Creates an empty 200 OK response. ### Signature ```rust pub fn reply() -> impl Reply ``` ### Returns A `Reply` that produces HTTP 200 with an empty body. ### Example ```rust use warp::Filter; let ok = warp::any().map(warp::reply); // Returns: HTTP/1.1 200 OK ``` ``` -------------------------------- ### RESTful API Pattern with Warp Filters Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/api-reference/filters-method-and-path.md Defines common RESTful operations (GET, POST, PUT, DELETE) for a 'users' resource using Warp's path and method filters. ```APIDOC ## GET /users ### Description Retrieves a list of all users. ### Method GET ### Endpoint /users ### Parameters None ### Request Example None ### Response #### Success Response (200) - `string` - A message indicating the action performed. #### Response Example ``` List users ``` ## GET /users/:id ### Description Retrieves a specific user by their ID. ### Method GET ### Endpoint /users/:id ### Parameters #### Path Parameters - **id** (u64) - Required - The unique identifier of the user. ### Request Example None ### Response #### Success Response (200) - `string` - A message indicating the action performed, including the user ID. #### Response Example ``` Get user 123 ``` ## POST /users ### Description Creates a new user. ### Method POST ### Endpoint /users ### Parameters None ### Request Example None ### Response #### Success Response (200) - `string` - A message indicating the action performed. #### Response Example ``` Create user ``` ## PUT /users/:id ### Description Updates an existing user identified by their ID. ### Method PUT ### Endpoint /users/:id ### Parameters #### Path Parameters - **id** (u64) - Required - The unique identifier of the user to update. ### Request Example None ### Response #### Success Response (200) - `string` - A message indicating the action performed, including the user ID. #### Response Example ``` Update user 123 ``` ## DELETE /users/:id ### Description Deletes a user identified by their ID. ### Method DELETE ### Endpoint /users/:id ### Parameters #### Path Parameters - **id** (u64) - Required - The unique identifier of the user to delete. ### Request Example None ### Response #### Success Response (200) - `string` - A message indicating the action performed, including the user ID. #### Response Example ``` Delete user 123 ``` ``` -------------------------------- ### trace() Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/api-reference/filters-advanced.md Logs all request details at trace level using the `tracing` crate. ```APIDOC ## trace() ### Description Logs all request details at trace level using the `tracing` crate. ### Method N/A (Filter wrapper) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use warp::Filter; let routes = warp::get() .and(warp::path("data")) .map(|| "data") .with(warp::trace("myapp::data")); ``` ### Response #### Success Response (200) N/A (Filter wrapper) #### Response Example N/A (Filter wrapper) **Logs at:** TRACE level using `tracing` crate ``` -------------------------------- ### Handling Length Required Error in Warp Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/errors.md This example shows how to handle a 411 Length Required error when the Content-Length header is missing for a request that requires a body. It uses `warp::body::content_length_limit()`. ```rust use warp::Filter; let upload = warp::body::content_length_limit(1024 * 1024) .and(warp::body::bytes()); // POST without Content-Length header -> 411 Length Required ``` -------------------------------- ### Curl Hello World Service Source: https://github.com/seanmonstar/warp/blob/master/examples/README.md Shows how to send a request to the running "hello world" Warp service using curl. ```bash > curl http://localhost:3030/hi Hello, World!% ``` -------------------------------- ### Basic Server-Side Event (SSE) Handling Source: https://github.com/seanmonstar/warp/blob/master/examples/README.md Demonstrates basic handling of Server-Sent Events (SSE) in Warp. ```rust use warp::Filter; use futures_util::{Stream, stream}; use std::convert::Infallible; #[tokio::main] async fn main() { let sse = warp::path("events") .and(warp::get()) .map(|| { let stream = stream::iter( (0..10).map(|i| Ok(format!("data: Event {}\n\n", i))) ); warp::sse::reply(stream) }); warp::serve(sse).run(([127, 0, 0, 1], 3030)).await; } ``` -------------------------------- ### Response Creation Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/README.md Documentation on how to create and customize HTTP responses using the `Reply` trait and various helper functions. Covers creating JSON, HTML, and streaming responses, and setting status codes and headers. ```APIDOC ## Response Creation ### Description This section explains how to construct HTTP responses using warp's `Reply` trait and associated helper functions. It provides tools for generating various response types and customizing their content and metadata. ### Core Trait - `Reply`: The trait implemented by types that can be converted into an HTTP response. ### Helper Functions - `reply(value: T)`: Creates a response from any type implementing `Reply`. - `json(value: T)`: Creates a JSON response. - `html(value: T)`: Creates an HTML response. - `stream(stream: S)`: Creates a streaming response. - `with_status(response: R, status: StatusCode)`: Sets the HTTP status code for a response. - `with_header(response: R, name: HeaderName, value: HeaderValue)`: Adds a header to a response. ``` -------------------------------- ### Handling Invalid Query Parameters in Warp Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/errors.md This example shows how to handle a 400 Bad Request error when query parameters fail to deserialize. It uses `warp::query::()` and expects a `u32` for the 'page' parameter. ```rust use serde::Deserialize; use warp::Filter; #[derive(Deserialize)] struct Query { page: u32 } let route = warp::query::(); // GET /?page=abc -> 400 Bad Request (not an integer) // GET /?page=1&unknown=x -> depends on deserializer ``` -------------------------------- ### Using Handlebars for HTML Templates Source: https://github.com/seanmonstar/warp/blob/master/examples/README.md Demonstrates integrating Handlebars templating engine to serve dynamic HTML content with Warp. ```rust use warp::Filter; use handlebars::Handlebars; #[tokio::main] async fn main() { let mut hbs = Handlebars::new(); hbs.register_template_string("template", "

Hello, {{name}}!

").unwrap(); let render = warp::path("render") .map(move || { let mut data = std::collections::HashMap::new(); data.insert("name", "World".to_string()); hbs.render("template", &data).unwrap() }); warp::serve(render).run(([127, 0, 0, 1], 3030)).await; } ``` -------------------------------- ### Debugging with Tracing Source: https://github.com/seanmonstar/warp/blob/master/examples/README.md Shows how to enable and use the `tracing` crate for rich diagnostics in Warp applications. ```rust use warp::Filter; use tracing_subscriber; #[tokio::main] async fn main() { // Initialize tracing subscriber tracing_subscriber::fmt::init(); let hello = warp::path("hello").map(|| "Hello, Traced World!"); // Warp automatically integrates with tracing warp::serve(hello).run(([127, 0, 0, 1], 3030)).await; } ``` -------------------------------- ### Extract Form Fields from Multipart Data Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/api-reference/multipart-and-specialized.md Process multipart form data to extract specific text fields like 'title' and 'body'. Use `part.name()` to identify fields and `part.text().await?` to get their string content. ```rust use warp::Filter; use futures_util::StreamExt; let submit = warp::post() .and(warp::multipart::form_data()) .and_then(|mut form: warp::multipart::FormData| async move { let mut title = String::new(); let mut body = String::new(); while let Some(part) = form.next().await { let part = part?; match part.name() { "title" => title = part.text().await?, "body" => body = part.text().await?, _ => {} } } Ok::<_, warp::Rejection>( warp::reply::json(&serde_json::json!({ "title": title, "body": body })) ) }); ``` -------------------------------- ### Serve a Single File Source: https://github.com/seanmonstar/warp/blob/master/_autodocs/api-reference/filters-advanced.md Use this filter to serve a specific file. It rejects with 404 if the file is not found, 403 if permissions are denied, or 500 for I/O errors. ```rust use warp::Filter; let index = warp::get() .and(warp::path::end()) .and(warp::fs::file("static/index.html")); let route = warp::path("download") .and(warp::fs::file("assets/document.pdf")); ```