### Basic Actix Web Application Setup Source: https://docs.rs/actix-web/latest/actix_web/index.html This example demonstrates the fundamental setup of an Actix Web application, including defining a simple GET route and starting the HTTP server. Ensure you have the necessary Actix Web dependencies in your Cargo.toml. ```rust use actix_web::{get, web, App, HttpServer, Responder}; #[get("/hello/{name}")] async fn greet(name: web::Path) -> impl Responder { format!("Hello {}!", name) } #[actix_web::main] // or #[tokio::main] async fn main() -> std::io::Result<()> { HttpServer::new(|| { App::new().service(greet) }) .bind(("127.0.0.1", 8080))? .run() .await } ``` -------------------------------- ### Resource Configuration Examples Source: https://docs.rs/actix-web/latest/actix_web/web/fn.resource.html Examples demonstrating how to configure routes for a resource, including GET and HEAD methods. ```APIDOC ## Resource Configuration Examples ### Description Examples demonstrating how to configure routes for a resource, including GET and HEAD methods. ### Method GET, HEAD ### Endpoint /users/{userid}/{friend} ### Parameters #### Path Parameters - **userid** (string) - Required - The user ID segment of the path. - **friend** (string) - Required - The friend segment of the path. ### Request Example ```json { "example": "GET /users/123/john" } ``` ### Response #### Success Response (200) - **HttpResponse** (HttpResponse) - OK response for GET requests. #### Error Response (405) - **HttpResponse** (HttpResponse) - MethodNotAllowed response for unsupported methods. #### Response Example ```json { "example": "HttpResponse::Ok() for GET, HttpResponse::MethodNotAllowed() for HEAD" } ``` ``` -------------------------------- ### Configure Route with GET Method and Header Guards Source: https://docs.rs/actix-web/latest/actix_web/struct.Route.html This example shows how to set up a route that specifically responds to GET requests and checks for a 'content-type' header. This is useful for defining precise request matching criteria. ```rust App::new().service(web::resource("/path").route( web::route() .guard(guard::Get()) .guard(guard::Header("content-type", "text/plain")) .to(|req: HttpRequest| HttpResponse::Ok())) ); ``` -------------------------------- ### HttpServer Example Source: https://docs.rs/actix-web/latest/actix_web/struct.HttpServer.html An example demonstrating how to create and run a basic Actix-web HTTP server. ```APIDOC ## HttpServer Example ### Description This example shows a minimal Actix-web application setup using `HttpServer`. ### Code ```rust use actix_web::{web, App, HttpResponse, HttpServer}; #[actix_web::main] async fn main() -> std::io::Result<()> { HttpServer::new(|| { App::new() .service(web::resource("/").to(|| async { "hello world" })) }) .bind(("127.0.0.1", 8080))? .run() .await } ``` ``` -------------------------------- ### Join Examples Source: https://docs.rs/actix-web/latest/actix_web/http/header/struct.AcceptCharset.html Examples demonstrating the usage of the join method for slices. ```APIDOC ## Join Examples ### Description Examples demonstrating the usage of the join method for slices. ### Code Examples ```rust assert_eq!(["hello", "world"].join(" "), "hello world"); assert_eq!([[1, 2], [3, 4]].join(&0), [1, 2, 0, 3, 4]); assert_eq!([[1, 2], [3, 4]].join(&[0, 0][..]), [1, 2, 0, 0, 3, 4]); ``` ``` -------------------------------- ### Basic HttpServer Example Source: https://docs.rs/actix-web/latest/actix_web/struct.HttpServer.html A basic example demonstrating how to create and run an actix-web server with a simple "hello world" service. ```rust use actix_web::{web, App, HttpResponse, HttpServer}; #[actix_web::main] async fn main() -> std::io::Result<()> { HttpServer::new(|| { App::new() .service(web::resource("/").to(|| async { "hello world" })) }) .bind(("127.0.0.1", 8080))? .run() .await } ``` -------------------------------- ### Run Actix Web Using #[tokio::main] Source: https://docs.rs/actix-web/latest/actix_web/rt/index.html This example shows how to run an Actix Web server within a `#[tokio::main]` async function. It uses the `#[get]` attribute macro for routing and the `run().await` method for server execution. Note that `actix` actor support still requires `#[actix_web::main]`. ```rust use actix_web::{get, middleware, rt, web, App, HttpRequest, HttpServer}; #[get("/")] async fn index(req: HttpRequest) -> &'static str { println!("REQ: {:?}", req); "Hello world!\r\n" } #[tokio::main] async fn main() -> std::io::Result<()> { HttpServer::new(|| { App::new().service(index) }) .bind(("127.0.0.1", 8080))?, .run() .await } ``` -------------------------------- ### Accept Header Construction Examples Source: https://docs.rs/actix-web/latest/actix_web/http/header/struct.Accept.html Examples demonstrating how to construct and insert `Accept` headers into HTTP requests using Actix-web's testing utilities. ```APIDOC ## Examples ### Example 1: Setting Accept to text/html ```rust use actix_web::{http::header::{Accept, QualityItem}, test}; let req = test::TestRequest::default() .insert_header(Accept(vec![QualityItem::max(mime::TEXT_HTML)])) .to_http_request(); ``` ### Example 2: Setting Accept to application/json ```rust use actix_web::{http::header::{Accept, QualityItem}, test}; let req = test::TestRequest::default() .insert_header(Accept(vec![QualityItem::max(mime::APPLICATION_JSON)])) .to_http_request(); ``` ### Example 3: Complex Accept Header ```rust use actix_web::{http::header::{Accept, Header as _, QualityItem, q}, test}; let req = test::TestRequest::default() .insert_header(Accept(vec![ QualityItem::max(mime::TEXT_HTML), QualityItem::max("application/xhtml+xml".parse().unwrap()), QualityItem::new(mime::TEXT_XML, q(0.9)), QualityItem::max("image/webp".parse().unwrap()), QualityItem::new(mime::STAR_STAR, q(0.8)), ])) .to_http_request(); let accept = Accept::parse(&req).unwrap(); assert_eq!(accept.preference(), mime::TEXT_HTML); ``` ``` -------------------------------- ### Basic Middleware Example Source: https://docs.rs/actix-web/latest/actix_web/middleware/fn.from_fn.html An example of a basic middleware function that can be used with `from_fn`. ```APIDOC ## GET /api/users/{id} ### Description Retrieves a specific user by their ID. ### Method GET ### Endpoint /api/users/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the user to retrieve. ### Response #### Success Response (200) - **id** (integer) - The unique identifier of the user. - **username** (string) - The username of the user. - **email** (string) - The email address of the user. #### Response Example ```json { "id": 123, "username": "johndoe", "email": "john.doe@example.com" } ``` ``` -------------------------------- ### Join Trait Examples Source: https://docs.rs/actix-web/latest/actix_web/http/header/struct.AcceptLanguage.html Examples demonstrating the usage of the join method for slices. ```APIDOC ## Examples for Join Trait ### Description Demonstrates how to use the `join` method to flatten slices with a separator. ### Examples ```rust assert_eq!(["hello", "world"].join(" "), "hello world"); assert_eq!([[1, 2], [3, 4]].join(&0), [1, 2, 0, 3, 4]); assert_eq!([[1, 2], [3, 4]].join(&[0, 0][..]), [1, 2, 0, 0, 3, 4]); ``` ``` -------------------------------- ### Uri Parsing and Examples Source: https://docs.rs/actix-web/latest/actix_web/http/uri/struct.Uri.html Demonstrates how to parse strings into Uri objects and provides examples of accessing URI components. ```APIDOC ## Uri Parsing and Examples ### Examples ```rust use http::Uri; // Parsing a relative path with query let uri = "/foo/bar?baz".parse::().unwrap(); assert_eq!(uri.path(), "/foo/bar"); assert_eq!(uri.query(), Some("baz")); assert_eq!(uri.host(), None); // Parsing an absolute URI let uri = "https://www.rust-lang.org/install.html".parse::().unwrap(); assert_eq!(uri.scheme_str(), Some("https")); assert_eq!(uri.host(), Some("www.rust-lang.org")); assert_eq!(uri.path(), "/install.html"); ``` ``` -------------------------------- ### UnixDatagram Examples Source: https://docs.rs/actix-web/latest/actix_web/rt/net/struct.UnixDatagram.html Examples demonstrating the usage of UnixDatagram for inter-process communication. ```APIDOC ## UnixDatagram Examples ### Description Examples demonstrating the usage of UnixDatagram for inter-process communication. ### For a peer with a local path ```rust use tokio::net::UnixDatagram; use tempfile::tempdir; // Create an unbound socket let tx = UnixDatagram::unbound()?; // Create another, bound socket let tmp = tempdir()?; let rx_path = tmp.path().join("rx"); let rx = UnixDatagram::bind(&rx_path)?; // Connect to the bound socket tx.connect(&rx_path)?; assert_eq!(tx.peer_addr()?.as_pathname().unwrap(), &rx_path); ``` ### For an unbound peer ```rust use tokio::net::UnixDatagram; // Create the pair of sockets let (sock1, sock2) = UnixDatagram::pair()?; assert!(sock1.peer_addr()?.is_unnamed()); ``` ``` -------------------------------- ### Uri Parsing Examples Source: https://docs.rs/actix-web/latest/actix_web/http/struct.Uri.html Examples demonstrating how to parse absolute and relative URIs, including those with query string components. ```APIDOC ## Uri Parsing Examples ### Absolute URI ```rust let uri: Uri = "http://example.org/hello/world?key=value".parse().unwrap(); assert_eq!(uri.query(), Some("key=value")); ``` ### Relative URI with a query string component ```rust let uri: Uri = "/hello/world?key=value&foo=bar".parse().unwrap(); assert_eq!(uri.query(), Some("key=value&foo=bar")); ``` ### Relative URI without a query string component ```rust let uri: Uri = "/hello/world".parse().unwrap(); assert!(uri.query().is_none()); ``` ``` -------------------------------- ### Range Header Construction Example Source: https://docs.rs/actix-web/latest/actix_web/http/header/enum.Range.html Example demonstrating how to insert `Range` headers into an Actix-web test request. ```APIDOC ## Examples ```rust use actix_web::{http::header::{ByteRangeSpec, Range}, test}; let req = test::TestRequest::default() .insert_header(Range::Bytes(vec![ ByteRangeSpec::FromTo(1, 100), ByteRangeSpec::From(200), ])) .insert_header(Range::Unregistered("letters".to_owned(), "a-f".to_owned())) .insert_header(Range::bytes(1, 100)) .insert_header(Range::bytes_multi(vec![(1, 100), (200, 300)])) .to_http_request(); ``` ``` -------------------------------- ### ETag Usage Examples Source: https://docs.rs/actix-web/latest/actix_web/http/header/struct.ETag.html Examples demonstrating how to insert ETag headers into HTTP responses using actix-web. ```APIDOC ## Examples ### Strong ETag Example ```rust use actix_web::HttpResponse; use actix_web::http::header::{ETag, EntityTag}; let mut builder = HttpResponse::Ok(); builder.insert_header( ETag(EntityTag::new_strong("xyzzy".to_owned())) ); ``` ### Weak ETag Example ```rust use actix_web::HttpResponse; use actix_web::http::header::{ETag, EntityTag}; let mut builder = HttpResponse::Ok(); builder.insert_header( ETag(EntityTag::new_weak("xyzzy".to_owned())) ); ``` ``` -------------------------------- ### Get Minute from UtcDateTime Source: https://docs.rs/actix-web/latest/actix_web/cookie/time/struct.UtcDateTime.html The `minute` method returns the minute component within the hour, in the range `0..60`. Examples verify the start and end of the minute range. ```rust assert_eq!(utc_datetime!(2019-01-01 0:00).minute(), 0); assert_eq!(utc_datetime!(2019-01-01 23:59:59).minute(), 59); ``` -------------------------------- ### Route Initialization and Configuration Source: https://docs.rs/actix-web/latest/actix_web/struct.Route.html Demonstrates how to create a new Route and apply middleware. ```APIDOC ## Route Initialization and Middleware ### Description Initializes a new Route and applies middleware to it. ### Method `new()` and `wrap()` ### Endpoint N/A (Struct methods) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust // To create a new route: let route = actix_web::Route::new(); // To wrap a route with middleware: // let wrapped_route = route.wrap(my_middleware); ``` ### Response #### Success Response (200) N/A (Struct methods) #### Response Example N/A ``` -------------------------------- ### Create a GET route with method guard Source: https://docs.rs/actix-web/latest/actix_web/web/fn.method.html Use this snippet to set up a route that only responds to GET requests. Ensure `actix_web` and `http` are imported. ```rust use actix_web::{web, http, App, HttpResponse}; let app = App::new().service( web::resource("/{project_id}") .route(web::method(http::Method::GET).to(|| HttpResponse::Ok())) ); ``` -------------------------------- ### Insert Allow Header with GET Method Source: https://docs.rs/actix-web/latest/actix_web/http/header/struct.Allow.html Example of inserting an Allow header with only the GET method into an HTTP response. ```rust use actix_web::HttpResponse; use actix_web::http::{header::Allow, Method}; let mut builder = HttpResponse::Ok(); builder.insert_header( Allow(vec![Method::GET]) ); ``` -------------------------------- ### GET Route Creation Source: https://docs.rs/actix-web/latest/actix_web/web/fn.get.html Demonstrates how to create a new route that specifically handles GET requests using `actix_web::web::get()`. ```APIDOC ## GET /:project_id ### Description Creates a new route with a `GET` method guard. This endpoint is designed to handle GET requests for a specific project ID. ### Method GET ### Endpoint `/{project_id}` ### Parameters #### Path Parameters - **project_id** (string) - Required - The identifier for the project. ### Request Example This endpoint does not require a request body for a GET request. ### Response #### Success Response (200) - **(empty)** - Returns an empty HttpResponse with Ok status. #### Response Example ``` HTTP/1.1 200 OK Content-Length: 0 ``` ## §Examples In this example, one `GET /{project_id}` route is set up: ```rust use actix_web::{web, App, HttpResponse}; let app = App::new().service( web::resource("/{project_id}") .route(web::get().to(|| HttpResponse::Ok())) ); ``` ``` -------------------------------- ### GET / Source: https://docs.rs/actix-web/latest/actix_web/web/struct.Query.html Example of extracting a typed struct from query parameters. ```APIDOC ## GET / ### Description This handler extracts typed data from the URL query string into an `AuthRequest` struct. ### Method GET ### Endpoint / ### Parameters #### Query Parameters - **id** (u64) - Required - The ID for the authorization request. - **response_type** (ResponseType) - Required - The type of response requested (Token or Code). ### Request Example ``` /?id=64&response_type=Code ``` ### Response #### Success Response (200) - **String** - A formatted string indicating the authorization request details. #### Response Example ``` Authorization request for id=64 and type=Code! ``` ``` -------------------------------- ### Resource Creation and Basic Usage Source: https://docs.rs/actix-web/latest/actix_web/struct.Resource.html Demonstrates how to create a new Resource for a given path and attach simple GET and POST routes with HttpResponse and async handlers. ```APIDOC ## POST /api/users ### Description Creates a new user. ### Method POST ### Endpoint /api/users ### Parameters #### Request Body - **username** (string) - Required - The username for the new user. - **email** (string) - Required - The email address for the new user. ### Request Example ```json { "username": "john_doe", "email": "john.doe@example.com" } ``` ### Response #### Success Response (201) - **id** (string) - The unique identifier for the newly created user. - **username** (string) - The username of the created user. - **email** (string) - The email address of the created user. #### Response Example ```json { "id": "a1b2c3d4-e5f6-7890-1234-567890abcdef", "username": "john_doe", "email": "john.doe@example.com" } ``` ``` -------------------------------- ### GET /debug2 Source: https://docs.rs/actix-web/latest/actix_web/web/struct.Query.html Example of accessing the inner deserialized value using destructuring. ```APIDOC ## GET /debug2 ### Description This handler shows how to use destructuring to access the deserialized query struct, which is equivalent to using `.into_inner()`. ### Method GET ### Endpoint /debug2 ### Parameters #### Query Parameters - **id** (u64) - Required - The ID for the authorization request. - **response_type** (ResponseType) - Required - The type of response requested (Token or Code). ### Request Example ``` /?id=64&response_type=Token ``` ### Response #### Success Response (200) - **String** - "OK" #### Response Example ``` OK ``` ``` -------------------------------- ### GET /debug1 Source: https://docs.rs/actix-web/latest/actix_web/web/struct.Query.html Example of accessing the inner deserialized value using `.into_inner()`. ```APIDOC ## GET /debug1 ### Description This handler demonstrates how to access the entire underlying deserialized query struct using the `.into_inner()` method. ### Method GET ### Endpoint /debug1 ### Parameters #### Query Parameters - **id** (u64) - Required - The ID for the authorization request. - **response_type** (ResponseType) - Required - The type of response requested (Token or Code). ### Request Example ``` /?id=64&response_type=Token ``` ### Response #### Success Response (200) - **String** - "OK" #### Response Example ``` OK ``` ``` -------------------------------- ### Server Build and Run Example Source: https://docs.rs/actix-web/latest/actix_web/dev/struct.Server.html An example demonstrating how to build and run a TCP echo server using actix-web's Server. This server listens on 127.0.0.1:8080 and echoes back any data received. ```APIDOC ## §Examples The following is a TCP echo server. Test using `telnet 127.0.0.1 8080`. ```rust use std::io; use actix_rt::net::TcpStream; use actix_server::Server; use actix_service::{fn_service, ServiceFactoryExt as _}; use bytes::BytesMut; use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; #[actix_rt::main] async fn main() -> io::Result<()> { let bind_addr = ("127.0.0.1", 8080); Server::build() .bind("echo", bind_addr, move || { fn_service(move |mut stream: TcpStream| { async move { let mut size = 0; let mut buf = BytesMut::new(); loop { match stream.read_buf(&mut buf).await { // end of stream; bail from loop Ok(0) => break, // write bytes back to stream Ok(bytes_read) => { stream.write_all(&buf[size..]).await.unwrap(); size += bytes_read; } Err(err) => { eprintln!("Stream Error: {:?}", err); return Err(()); } } } Ok(()) } }) .map_err(|err| eprintln!("Service Error: {:?}", err)) })? .run() .await } ``` ``` -------------------------------- ### Mime::subtype() Example Source: https://docs.rs/actix-web/latest/actix_web/http/header/struct.ContentType.html Demonstrates how to get the subtype (e.g., 'plain') from a Mime object. ```rust let mime = mime::TEXT_PLAIN; assert_eq!(mime.subtype(), "plain"); assert_eq!(mime.subtype(), mime::PLAIN); ``` -------------------------------- ### Mime::type_() Example Source: https://docs.rs/actix-web/latest/actix_web/http/header/struct.ContentType.html Demonstrates how to get the top-level media type (e.g., 'text') from a Mime object. ```rust let mime = mime::TEXT_PLAIN; assert_eq!(mime.type_(), "text"); assert_eq!(mime.type_(), mime::TEXT); ``` -------------------------------- ### Example: One to Many (Bind) Source: https://docs.rs/actix-web/latest/actix_web/rt/net/struct.UdpSocket.html Demonstrates how to use `bind`, `recv_from`, and `send_to` to create a simple UDP echo server that can communicate with multiple clients. ```APIDOC ## Example: one to many (bind) Using `bind` we can create a simple echo server that sends and recv’s with many different clients: ```rust use tokio::net::UdpSocket; use std::io; #[tokio::main] async fn main() -> io::Result<()> { let sock = UdpSocket::bind("0.0.0.0:8080").await?; let mut buf = [0; 1024]; loop { let (len, addr) = sock.recv_from(&mut buf).await?; println!("{:?} bytes received from {:?}", len, addr); let len = sock.send_to(&buf[..len], addr).await?; println!("{:?} bytes sent", len); } } ``` ``` -------------------------------- ### Get Uri Query String Source: https://docs.rs/actix-web/latest/actix_web/http/struct.Uri.html Retrieves the query string of a Uri, which starts after the '?' and is terminated by '#' or the end of the URI. ```rust abc://username:password@example.com:123/path/data?key=value&key2=value2#fragid1 |----------------------------------| | query ``` -------------------------------- ### String Extractor Example Source: https://docs.rs/actix-web/latest/actix_web/trait.FromRequest.html Example of using the `String` extractor to get text data from a request body. The extractor automatically decodes the body based on the request's charset. Configure extraction using `PayloadConfig`. ```rust use actix_web::{post, web, FromRequest}; // extract text data from request #[post("/")] async fn index(text: String) -> String { format!("Body {}!", text) } ``` -------------------------------- ### CookieJar - Initialization and Basic Usage Source: https://docs.rs/actix-web/latest/actix_web/cookie/struct.CookieJar.html Demonstrates how to create a new CookieJar and add original cookies to it. ```APIDOC ## CookieJar - Initialization and Basic Usage ### Description This section shows how to initialize an empty `CookieJar` and add original cookies to it. Original cookies are typically received from an HTTP request and do not affect the delta calculation. ### Method `CookieJar::new()` and `CookieJar::add_original()` ### Endpoint N/A (Struct method) ### Request Body N/A ### Request Example ```rust use cookie::{Cookie, CookieJar}; let mut jar = CookieJar::new(); jar.add_original(Cookie::new("name", "value")); jar.add_original(Cookie::new("second", "another")); ``` ### Response #### Success Response (200) N/A (This is a client-side struct) #### Response Example N/A ``` -------------------------------- ### Get Current Instant Source: https://docs.rs/actix-web/latest/actix_web/rt/time/struct.Instant.html Returns an instant corresponding to the current time. This is the basic way to start measuring time. ```rust use tokio::time::Instant; let now = Instant::now(); ``` -------------------------------- ### System Creation Source: https://docs.rs/actix-web/latest/actix_web/rt/struct.System.html Methods for creating a new System instance. ```APIDOC ## System Creation ### Description Methods for creating a new System instance. ### `new()` Creates a new system. This method is available on non-crate feature `io-uring` only. **Panics** Panics if the underlying Tokio runtime cannot be created. ### `with_tokio_rt()` Creates a new System using the Tokio Runtime returned from a closure. This method is available on non-crate feature `io-uring` only. - **runtime_factory** (FnOnce() -> Runtime) - A closure that returns a Tokio Runtime. ``` -------------------------------- ### Create WebService with Guard Source: https://docs.rs/actix-web/latest/actix_web/dev/struct.WebService.html Demonstrates how to create a new WebService instance, apply a header guard, and finish the service configuration with an index handler. Ensure the necessary imports are present. ```rust use actix_web::{web, guard, dev, App, Error, HttpResponse}; async fn index(req: dev::ServiceRequest) -> Result { Ok(req.into_response(HttpResponse::Ok().finish())) } let app = App::new() .service( web::service("/app") .guard(guard::Header("content-type", "text/plain")) .finish(index) ); ``` -------------------------------- ### Example: Resume panic from JoinError Source: https://docs.rs/actix-web/latest/actix_web/rt/task/struct.JoinError.html This example shows how to safely extract and resume a panic from a `JoinError`. It first checks if the error is a panic using `is_panic`, then uses `into_panic` to get the panic payload and `panic::resume_unwind` to re-throw it. ```rust use std::panic; #[tokio::main] async fn main() { let err = tokio::spawn(async { panic!("boom"); }).await.unwrap_err(); if err.is_panic() { // Resume the panic on the main task panic::resume_unwind(err.into_panic()); } } ``` -------------------------------- ### Example: Safely get panic payload from JoinError Source: https://docs.rs/actix-web/latest/actix_web/rt/task/struct.JoinError.html This example demonstrates using `try_into_panic` to safely extract a panic payload. If the `JoinError` represents a panic, the payload is retrieved and used to resume the panic. Otherwise, the original error is handled. ```rust use std::panic; #[tokio::main] async fn main() { let err = tokio::spawn(async { panic!("boom"); }).await.unwrap_err(); if let Ok(reason) = err.try_into_panic() { // Resume the panic on the main task panic::resume_unwind(reason); } } ``` -------------------------------- ### ResourceDef Matching Examples Source: https://docs.rs/actix-web/latest/actix_web/dev/struct.ResourceDef.html Demonstrates various ways to define and match resources using ResourceDef, including static, constant prefix, dynamic prefix, and multi-pattern resources. ```APIDOC ## ResourceDef Matching Examples ### Description Examples of defining and matching resources using `ResourceDef`. ### Examples ```rust use actix_router::ResourceDef; // static resource let resource = ResourceDef::new("/user"); assert_eq!(resource.find_match("/user"), Some(5)); assert!(resource.find_match("/user/").is_none()); assert!(resource.find_match("/user/123").is_none()); assert!(resource.find_match("/foo").is_none()); // constant prefix resource let resource = ResourceDef::prefix("/user"); assert_eq!(resource.find_match("/user"), Some(5)); assert_eq!(resource.find_match("/user/"), Some(5)); assert_eq!(resource.find_match("/user/123"), Some(5)); // dynamic prefix resource let resource = ResourceDef::prefix("/user/{id}"); assert_eq!(resource.find_match("/user/123"), Some(9)); assert_eq!(resource.find_match("/user/1234/"), Some(10)); assert_eq!(resource.find_match("/user/12345/stars"), Some(11)); assert!(resource.find_match("/user/").is_none()); // multi-pattern resource let resource = ResourceDef::new(["/user/{id}", "/profile/{id}"]); assert_eq!(resource.find_match("/user/123"), Some(9)); assert_eq!(resource.find_match("/profile/1234"), Some(13)); ``` ``` -------------------------------- ### Serving Pre-compressed Gzip File Source: https://docs.rs/actix-web/latest/actix_web/middleware/struct.Compress.html This example shows how to serve a pre-compressed Gzip file while correctly configuring headers to bypass the Compress middleware and inform the client. ```APIDOC ## GET /items/{id} ### Description Retrieves a specific item by its unique identifier. ### Method GET ### Endpoint /items/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the item to retrieve. #### Query Parameters - **include_details** (boolean) - Optional - Whether to include detailed information about the item. ### Response #### Success Response (200) - **id** (integer) - The unique identifier of the item. - **name** (string) - The name of the item. - **description** (string) - A description of the item (optional, included if `include_details` is true). #### Response Example ```json { "id": 123, "name": "Example Item", "description": "This is a detailed description of the example item." } ``` ``` -------------------------------- ### Route Guard Example with Method and Header Source: https://docs.rs/actix-web/latest/actix_web/guard/index.html This example demonstrates a route that is guarded by both HTTP method (GET or POST) and a specific request header ('x-guarded' with value 'secret'). Use this when a route should only respond to specific methods and header conditions. ```rust use actix_web::{web, http::Method, guard, HttpResponse}; web::resource("/guarded").route( web::route() .guard(guard::Any(guard::Get()).or(guard::Post())) .guard(guard::Header("x-guarded", "secret")) .to(|| HttpResponse::Ok()) ); ``` -------------------------------- ### Iterate over a slice Source: https://docs.rs/actix-web/latest/actix_web/http/header/struct.CacheControl.html Use `iter()` to get an immutable iterator over slice elements. The iterator yields items from start to end. ```rust let x = &[1, 2, 4]; let mut iterator = x.iter(); assert_eq!(iterator.next(), Some(&1)); assert_eq!(iterator.next(), Some(&2)); assert_eq!(iterator.next(), Some(&4)); assert_eq!(iterator.next(), None); ``` -------------------------------- ### Example: One to One (Connect) Source: https://docs.rs/actix-web/latest/actix_web/rt/net/struct.UdpSocket.html Illustrates how to use `connect`, `send`, and `recv` for a UDP communication pattern where the socket is associated with a single remote address. ```APIDOC ## Example: one to one (connect) Or using `connect` we can echo with a single remote address using `send` and `recv`: ```rust use tokio::net::UdpSocket; use std::io; #[tokio::main] async fn main() -> io::Result<()> { let sock = UdpSocket::bind("0.0.0.0:8080").await?; let remote_addr = "127.0.0.1:59611"; sock.connect(remote_addr).await?; let mut buf = [0; 1024]; loop { let len = sock.recv(&mut buf).await?; println!("{:?} bytes received from {:?}", len, remote_addr); let len = sock.send(&buf[..len]).await?; println!("{:?} bytes sent", len); } } ``` ``` -------------------------------- ### Get Day Number from Sunday (0-indexed) Source: https://docs.rs/actix-web/latest/actix_web/cookie/time/enum.Weekday.html Returns the zero-indexed position of the weekday, starting with Sunday as 0. Requires the 'cookies' feature. ```rust assert_eq!(Weekday::Monday.number_days_from_sunday(), 1); ``` -------------------------------- ### Virtual Hosting with Host Guards Source: https://docs.rs/actix-web/latest/actix_web/guard/fn.Host.html Demonstrates setting up virtual hosting within a single app using Host guards. This allows different services to be accessible based on the host name. ```rust use actix_web::{web, http::Method, guard, App, HttpResponse}; App::new() .service( web::scope("") .guard(guard::Host("www.rust-lang.org")) .default_service(web::to(|| async { HttpResponse::Ok().body("marketing site") })), ) .service( web::scope("") .guard(guard::Host("play.rust-lang.org")) .default_service(web::to(|| async { HttpResponse::Ok().body("playground frontend") })), ); ``` -------------------------------- ### Create and Match Resource Definitions Source: https://docs.rs/actix-web/latest/actix_web/dev/struct.ResourceDef.html Demonstrates creating ResourceDef instances with different patterns and testing their matching capabilities against various paths. Use ResourceDef::root_prefix for root-level patterns. ```rust use actix_router::ResourceDef; let resource = ResourceDef::root_prefix("user/{id}"); assert_eq!(&resource, &ResourceDef::prefix("/user/{id}")); assert_eq!(&resource, &ResourceDef::root_prefix("/user/{id}")); assert_ne!(&resource, &ResourceDef::new("user/{id}")); assert_ne!(&resource, &ResourceDef::new("/user/{id}")); assert!(resource.is_match("/user/123")); assert!(!resource.is_match("user/123")); ``` -------------------------------- ### Get Day Number from Monday (0-indexed) Source: https://docs.rs/actix-web/latest/actix_web/cookie/time/enum.Weekday.html Returns the zero-indexed position of the weekday, starting with Monday as 0. Requires the 'cookies' feature. ```rust assert_eq!(Weekday::Monday.number_days_from_monday(), 0); ``` -------------------------------- ### Get Day Number from Sunday (1-indexed) Source: https://docs.rs/actix-web/latest/actix_web/cookie/time/enum.Weekday.html Returns the one-indexed position of the weekday, starting with Sunday as 1. Requires the 'cookies' feature. ```rust assert_eq!(Weekday::Monday.number_from_sunday(), 2); ``` -------------------------------- ### ResourceDef Construction and Basic Usage Source: https://docs.rs/actix-web/latest/actix_web/dev/struct.ResourceDef.html Demonstrates how to create and use ResourceDef with different patterns and checks for equality. ```APIDOC ## ResourceDef Construction and Basic Usage ### Description This section shows how to construct `ResourceDef` instances with various patterns and how to compare them. ### Method `ResourceDef::root_prefix`, `ResourceDef::prefix`, `ResourceDef::new` ### Endpoint N/A (Struct methods) ### Request Body N/A ### Request Example ```rust use actix_router::ResourceDef; let resource = ResourceDef::root_prefix("user/{id}"); assert_eq!(&resource, &ResourceDef::prefix("/user/{id}")); assert_eq!(&resource, &ResourceDef::root_prefix("/user/{id}")); assert_ne!(&resource, &ResourceDef::new("user/{id}")); assert_ne!(&resource, &ResourceDef::new("/user/{id}")); ``` ### Response N/A (Illustrative assertions) ``` -------------------------------- ### Get Day Number from Monday (1-indexed) Source: https://docs.rs/actix-web/latest/actix_web/cookie/time/enum.Weekday.html Returns the one-indexed position of the weekday, starting with Monday as 1. Requires the 'cookies' feature. ```rust assert_eq!(Weekday::Monday.number_from_monday(), 1); ``` -------------------------------- ### Example: Using IfMatch::Any Source: https://docs.rs/actix-web/latest/actix_web/http/header/enum.IfMatch.html Demonstrates how to insert the IfMatch::Any header into an HTTP request using actix-web's test utilities. ```rust use actix_web::{http::header::IfMatch, test}; let req = test::TestRequest::default() .insert_header(IfMatch::Any) .to_http_request(); ``` -------------------------------- ### Mime::suffix() Example Source: https://docs.rs/actix-web/latest/actix_web/http/header/struct.ContentType.html Demonstrates how to get an optional suffix (e.g., 'xml' from 'image/svg+xml') from a Mime object. Returns None if no suffix is present. ```rust let svg = "image/svg+xml".parse::().unwrap(); assert_eq!(svg.suffix(), Some(mime::XML)); assert_eq!(svg.suffix().unwrap(), "xml"); assert!(mime::TEXT_PLAIN.suffix().is_none()); ``` -------------------------------- ### Iterate and modify a slice Source: https://docs.rs/actix-web/latest/actix_web/http/header/struct.CacheControl.html Use `iter_mut()` to get a mutable iterator for modifying slice elements. The iterator yields items from start to end. ```rust let x = &mut [1, 2, 4]; for elem in x.iter_mut() { *elem += 2; } assert_eq!(x, &[3, 4, 6]); ``` -------------------------------- ### Quality Value Examples Source: https://docs.rs/actix-web/latest/actix_web/http/header/struct.Quality.html Demonstrates creating and comparing Quality values using the q() function and accessing constants like MAX, MIN, and ZERO. Also shows string representation. ```rust use actix_http::header::{Quality, q}; assert_eq!(q(1.0), Quality::MAX); assert_eq!(q(0.42).to_string(), "0.42"); assert_eq!(q(1.0).to_string(), "1"); assert_eq!(Quality::MIN.to_string(), "0.001"); assert_eq!(Quality::ZERO.to_string(), "0"); ``` -------------------------------- ### Insert Allow Header with Multiple Methods Source: https://docs.rs/actix-web/latest/actix_web/http/header/struct.Allow.html Example of inserting an Allow header with multiple HTTP methods (GET, POST, PATCH) into an HTTP response. ```rust use actix_web::HttpResponse; use actix_web::http::{header::Allow, Method}; let mut builder = HttpResponse::Ok(); builder.insert_header( Allow(vec![ Method::GET, Method::POST, Method::PATCH, ]) ); ``` -------------------------------- ### Handler Using PeerAddr Extractor Source: https://docs.rs/actix-web/latest/actix_web/dev/struct.PeerAddr.html Example of an asynchronous handler function that uses PeerAddr as an extractor to get the peer's socket address and return it as a string. ```rust use actix_web::dev::PeerAddr; async fn handler(peer_addr: PeerAddr) -> impl Responder { let socket_addr = peer_addr.0; socket_addr.to_string() } ``` -------------------------------- ### Example: Inserting Headers Source: https://docs.rs/actix-web/latest/actix_web/struct.HttpResponseBuilder.html Demonstrates how to insert headers using `insert_header` to set the Content-Type and a custom header. ```APIDOC ## POST /api/example ### Description This endpoint demonstrates inserting headers into an HTTP response. ### Method POST ### Endpoint /api/example ### Request Body (Not specified in the provided text) ### Response #### Success Response (200) - `HttpResponse` (HttpResponse) - The constructed HTTP response. ### Request Example (Not specified in the provided text) ### Response Example ```rust use actix_web::{HttpResponse, http::header}; HttpResponse::Ok() .insert_header(header::ContentType(mime::APPLICATION_JSON)) .insert_header(("X-TEST", "value")) .finish(); ``` ``` -------------------------------- ### Get Sunday-Based Week Number - Actix Web DateTime Source: https://docs.rs/actix-web/latest/actix_web/cookie/time/struct.OffsetDateTime.html Determine the week number where week 1 starts on a Sunday. The output ranges from 0 to 53. ```rust assert_eq!(datetime!(2019-01-01 0:00 UTC).sunday_based_week(), 0); assert_eq!(datetime!(2020-01-01 0:00 UTC).sunday_based_week(), 0); assert_eq!(datetime!(2020-12-31 0:00 UTC).sunday_based_week(), 52); assert_eq!(datetime!(2021-01-01 0:00 UTC).sunday_based_week(), 0); ``` -------------------------------- ### Scope Creation and Usage Source: https://docs.rs/actix-web/latest/actix_web/struct.Scope.html Demonstrates how to create a new Scope and register services within it. It also shows how to define routes with different HTTP methods and dynamic path segments. ```APIDOC ## POST /api/users ### Description Creates a new user in the system. ### Method POST ### Endpoint /api/users ### Parameters #### Request Body - **username** (string) - Required - The username for the new user. - **email** (string) - Required - The email address for the new user. ### Request Example ```json { "username": "johndoe", "email": "john.doe@example.com" } ``` ### Response #### Success Response (201) - **id** (string) - The unique identifier for the newly created user. - **username** (string) - The username of the created user. - **email** (string) - The email address of the created user. #### Response Example ```json { "id": "123e4567-e89b-12d3-a456-426614174000", "username": "johndoe", "email": "john.doe@example.com" } ``` ``` -------------------------------- ### Get Monday-Based Week Number from UtcDateTime Source: https://docs.rs/actix-web/latest/actix_web/cookie/time/struct.UtcDateTime.html Retrieves the week number (0-53) where week 1 starts on Monday. Use for standard business week calculations. ```rust assert_eq!(utc_datetime!(2019-01-01 0:00).monday_based_week(), 0); ``` ```rust assert_eq!(utc_datetime!(2020-01-01 0:00).monday_based_week(), 0); ``` ```rust assert_eq!(utc_datetime!(2020-12-31 0:00).monday_based_week(), 52); ``` ```rust assert_eq!(utc_datetime!(2021-01-01 0:00).monday_based_week(), 0); ``` -------------------------------- ### Run Actix Web Without Macros Source: https://docs.rs/actix-web/latest/actix_web/rt/index.html This example demonstrates how to run an Actix Web server using `rt::System::new().block_on()` without relying on procedural macros for routing. It sets up a basic HTTP server that responds to requests on the root path. ```rust use actix_web::{middleware, rt, web, App, HttpRequest, HttpServer}; async fn index(req: HttpRequest) -> &'static str { println!("REQ: {:?}", req); "Hello world!\r\n" } fn main() -> std::io::Result<()> { rt::System::new().block_on( HttpServer::new(|| { App::new().service(web::resource("/").route(web::get().to(index))) }) .bind(("127.0.0.1", 8080))?, .run() ) } ``` -------------------------------- ### Get Nanosecond from UtcDateTime Source: https://docs.rs/actix-web/latest/actix_web/cookie/time/struct.UtcDateTime.html The `nanosecond` method returns the nanosecond component within the second, in the range `0..1_000_000_000`. Examples verify zero and maximum nanoseconds. ```rust assert_eq!(utc_datetime!(2019-01-01 0:00).nanosecond(), 0); assert_eq!( utc_datetime!(2019-01-01 23:59:59.999_999_999).nanosecond(), 999_999_999, ); ``` -------------------------------- ### Get Millisecond from UtcDateTime Source: https://docs.rs/actix-web/latest/actix_web/cookie/time/struct.UtcDateTime.html The `millisecond` method returns the millisecond component within the second, in the range `0..1_000`. Examples verify zero and maximum milliseconds. ```rust assert_eq!(utc_datetime!(2019-01-01 0:00).millisecond(), 0); assert_eq!(utc_datetime!(2019-01-01 23:59:59.999).millisecond(), 999); ``` -------------------------------- ### Initialize and Test an Actix-web Service Source: https://docs.rs/actix-web/latest/actix_web/test/fn.init_service.html This example demonstrates how to initialize an Actix-web service using `test::init_service` and then make a test request to it. Ensure the `#[actix_web::test]` attribute is used for asynchronous test functions. ```rust use actix_service::Service; use actix_web::{test, web, App, HttpResponse, http::StatusCode}; #[actix_web::test] async fn test_init_service() { let app = test::init_service( App::new() .service(web::resource("/test").to(|| async { "OK" })) ).await; // Create request object let req = test::TestRequest::with_uri("/test").to_request(); // Execute application let res = app.call(req).await.unwrap(); assert_eq!(res.status(), StatusCode::OK); } ``` -------------------------------- ### Reverse Split Slice by Predicate Source: https://docs.rs/actix-web/latest/actix_web/http/header/struct.CacheControl.html Use `rsplit` to get an iterator over subslices separated by elements matching a predicate, starting from the end of the slice. The matched element is not included. ```rust let slice = [10, 40, 33, 20]; let mut iter = slice.rsplit(|num| num % 3 == 0); assert_eq!(iter.next().unwrap(), &[20]); assert_eq!(iter.next().unwrap(), &[10, 40]); assert!(iter.next().is_none()); ``` -------------------------------- ### Get Sunday-Based Week Number from UtcDateTime Source: https://docs.rs/actix-web/latest/actix_web/cookie/time/struct.UtcDateTime.html Retrieves the week number (0-53) where week 1 starts on Sunday. Useful for calendars where Sunday is the first day of the week. ```rust assert_eq!(utc_datetime!(2019-01-01 0:00).sunday_based_week(), 0); ``` ```rust assert_eq!(utc_datetime!(2020-01-01 0:00).sunday_based_week(), 0); ``` ```rust assert_eq!(utc_datetime!(2020-12-31 0:00).sunday_based_week(), 52); ``` ```rust assert_eq!(utc_datetime!(2021-01-01 0:00).sunday_based_week(), 0); ``` -------------------------------- ### Define and Match Static, Constant, and Dynamic Prefix Resources Source: https://docs.rs/actix-web/latest/actix_web/dev/struct.ResourceDef.html Demonstrates creating ResourceDef for static paths, constant prefixes, and dynamic prefixes with path matching. ```rust use actix_router::ResourceDef; // static resource let resource = ResourceDef::new("/user"); assert_eq!(resource.find_match("/user"), Some(5)); assert!(resource.find_match("/user/").is_none()); assert!(resource.find_match("/user/123").is_none()); assert!(resource.find_match("/foo").is_none()); // constant prefix resource let resource = ResourceDef::prefix("/user"); assert_eq!(resource.find_match("/user"), Some(5)); assert_eq!(resource.find_match("/user/"), Some(5)); assert_eq!(resource.find_match("/user/123"), Some(5)); // dynamic prefix resource let resource = ResourceDef::prefix("/user/{id}"); assert_eq!(resource.find_match("/user/123"), Some(9)); assert_eq!(resource.find_match("/user/1234/"), Some(10)); assert_eq!(resource.find_match("/user/12345/stars"), Some(11)); assert!(resource.find_match("/user/").is_none()); // multi-pattern resource let resource = ResourceDef::new(["/user/{id}", "/profile/{id}"]); assert_eq!(resource.find_match("/user/123"), Some(9)); assert_eq!(resource.find_match("/profile/1234"), Some(13)); ``` -------------------------------- ### Get Current Buffer Chunk Source: https://docs.rs/actix-web/latest/actix_web/web/struct.Bytes.html The `chunk` method from the `Buf` trait returns a slice of available bytes starting from the current position. The returned slice length can be less than `Buf::remaining()`. ```rust fn chunk(&self) -> &[u8] ``` -------------------------------- ### Iterate Over Exact Slice Chunks from the End Source: https://docs.rs/actix-web/latest/actix_web/http/header/struct.AcceptLanguage.html Use `rchunks_exact` to get an iterator over slices of exactly `chunk_size`, starting from the end. Elements not fitting into a full chunk are omitted. Panics if `chunk_size` is zero. ```rust let slice = ['l', 'o', 'r', 'e', 'm']; let mut iter = slice.rchunks_exact(2); assert_eq!(iter.next().unwrap(), &['e', 'm']); assert_eq!(iter.next().unwrap(), &['o', 'r']); assert!(iter.next().is_none()); // The remainder can be retrieved using the .remainder() method assert_eq!(iter.remainder(), &['l']); ```