### Basic Actix Web Server Setup Source: https://docs.rs/actix-web/4.11.0/actix_web/index.html This example demonstrates how to set up a basic Actix Web server with a single GET route. It requires the `actix_web` crate and uses the `#[actix_web::main]` macro for asynchronous execution. ```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 } ``` -------------------------------- ### Example: Accessing and Using Actix Runtime Source: https://docs.rs/actix-web/4.11.0/actix_web/rt/struct.SystemRunner.html Demonstrates how to get a reference to the Actix runtime from a SystemRunner and use it to spawn an async task. ```rust let system_runner = actix_rt::System::new(); let actix_runtime = system_runner.runtime(); // Use the runtime to spawn an async task or perform other operations ``` -------------------------------- ### Define a Prefix Resource Source: https://docs.rs/actix-web/4.11.0/actix_web/dev/struct.ResourceDef.html Use ResourceDef::prefix to create a resource that matches the start of a path. This example demonstrates matching '/home' and paths starting with it. ```rust let resource = ResourceDef::prefix("/home"); assert!(resource.is_match("/home")); assert!(resource.is_match("/home/new")); assert!(!resource.is_match("/homes")); ``` -------------------------------- ### UnixDatagram Peer Connection Examples Source: https://docs.rs/actix-web/4.11.0/actix_web/rt/net/struct.UnixDatagram.html Examples demonstrating how to establish connections between UnixDatagram sockets, both for bound and unbound peers. ```APIDOC ## UnixDatagram Peer Connection Examples ### Description Examples demonstrating how to establish connections between UnixDatagram sockets, both for bound and unbound peers. ### Examples #### 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/4.11.0/actix_web/http/struct.Uri.html Examples demonstrating how to parse absolute and relative URIs, including those with query strings. ```APIDOC ## Parsing URIs ### 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()); ``` ``` -------------------------------- ### Create GET Route with Resource Source: https://docs.rs/actix-web/4.11.0/actix_web/web/fn.get.html Sets up a GET route for a specific resource path. This is useful for defining endpoints that respond to GET requests. ```rust use actix_web::{web, App, HttpResponse}; let app = App::new().service( web::resource("/{project_id}") .route(web::get().to(|| HttpResponse::Ok())) ); ``` -------------------------------- ### Basic HttpServer Example Source: https://docs.rs/actix-web/4.11.0/actix_web/struct.HttpServer.html A simple example demonstrating how to create an HTTP server, bind it to an address, and run a basic application. ```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 } ``` -------------------------------- ### Route Example with Method and Header Guards Source: https://docs.rs/actix-web/4.11.0/src/actix_web/route.rs.html Demonstrates how to configure a route using `web::resource` and `web::get()` to specify the HTTP method and a header guard for content-type. ```rust # use actix_web::http; # use actix_web::guard; # use actix_web::{web, App, HttpRequest, HttpResponse}; # fn main() { App::new().service(web::resource("/path").route( web::get() .method(http::Method::CONNECT) .guard(guard::Header("content-type", "text/plain")) .to(|req: HttpRequest| HttpResponse::Ok())) ); # } ``` -------------------------------- ### Test Parsing and Formatting of Allow Header (RFC Example) Source: https://docs.rs/actix-web/4.11.0/src/actix_web/http/header/allow.rs.html Tests the parsing and formatting of the Allow header according to the RFC example 'GET, HEAD, PUT'. ```rust crate::http::header::common_header_test!( test1, [b"GET, HEAD, PUT"], Some(HeaderField(vec![Method::GET, Method::HEAD, Method::PUT]))); ``` -------------------------------- ### Logger Usage Example Source: https://docs.rs/actix-web/4.11.0/actix_web/middleware/struct.Logger.html Example of how to initialize logging and wrap the Logger middleware in an Actix-web application. ```APIDOC ## Logger Usage Example ### Description This example demonstrates how to set up the `env_logger` and apply the `Logger` middleware to an Actix-web application. ### Code Example ```rust use actix_web::{middleware::Logger, App}; // Access logs are printed with the INFO level, so ensure it is enabled by default. env_logger::init_from_env(env_logger::Env::new().default_filter_or("info")); let app = App::new() // .wrap(Logger::default()) .wrap(Logger::new("%a %{User-Agent}i")); ``` ``` -------------------------------- ### Create GET Request Guard Source: https://docs.rs/actix-web/4.11.0/actix_web/guard/fn.Get.html Use this guard to ensure a route only responds to GET requests. No additional setup is required beyond importing the necessary modules. ```rust use actix_web::{guard, web, HttpResponse}; web::route() .guard(guard::Get()) .to(|| HttpResponse::Ok()); ``` -------------------------------- ### WebService Creation and Configuration Source: https://docs.rs/actix-web/4.11.0/actix_web/dev/struct.WebService.html Demonstrates how to create a new WebService, set its name, add guards, and attach a service. ```APIDOC ## POST /api/users ### Description Creates a new user in the system. ### Method POST ### Endpoint /api/users ### Parameters #### Query Parameters - **name** (string) - Required - The name of the user. #### Request Body - **email** (string) - Required - The email address of the user. - **password** (string) - Required - The password for the user. ### Request Example ```json { "email": "user@example.com", "password": "securepassword" } ``` ### Response #### Success Response (201) - **id** (string) - The unique identifier of the created user. - **message** (string) - A confirmation message. #### Response Example ```json { "id": "user-12345", "message": "User created successfully." } ``` ``` -------------------------------- ### Get Sunday-Based Week Number Source: https://docs.rs/actix-web/4.11.0/actix_web/cookie/time/struct.OffsetDateTime.html Retrieves the week number where week 1 starts on Sunday (0-53). Shows how the week number resets at the start of a new year. ```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); ``` -------------------------------- ### Runtime Initialization and Usage Source: https://docs.rs/actix-web/4.11.0/actix_web/rt/struct.Runtime.html Demonstrates how to create a new `Runtime` instance and spawn futures onto it. ```APIDOC ## POST /api/users ### Description Creates a new user in the system. ### Method POST ### Endpoint /api/users ### Parameters #### Request Body - **username** (string) - Required - The desired username for the new user. - **email** (string) - Required - The email address of the new user. - **password** (string) - Required - The password for the new user. ### Request Example ```json { "username": "johndoe", "email": "john.doe@example.com", "password": "securepassword123" } ``` ### 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": "johndoe", "email": "john.doe@example.com" } ``` ``` -------------------------------- ### Either Responder Example Source: https://docs.rs/actix-web/4.11.0/actix_web/web/enum.Either.html This example shows how to use the Either enum as a responder to return different types of responses, such as a simple string or a structured HTTP response, from a GET request. ```APIDOC ## GET /api/response ### Description Returns either a simple string message or a structured HTML response based on a condition. ### Method GET ### Endpoint / ### Response #### Success Response (200) - **Either<&'static str, Result>** - The response, which can be a static string or an HttpResponse. #### Response Example (String) ``` Bad data ``` #### Response Example (HTML) ```html

Hello!

``` ``` -------------------------------- ### Example: Resource with Default Service Source: https://docs.rs/actix-web/4.11.0/src/actix_web/resource.rs.html Demonstrates how to create a resource with a specific route and a custom default service that returns a BadRequest response. ```rust let resource = web::resource("/test") .route(web::get().to(HttpResponse::Ok)) .default_service(web::to(|| { HttpResponse::BadRequest() })); App::new().service(resource); ``` -------------------------------- ### Example: Safely extract and resume panic Source: https://docs.rs/actix-web/4.11.0/actix_web/rt/task/struct.JoinError.html This example demonstrates using `try_into_panic` to safely get the panic payload from a JoinError. If successful, it resumes the panic; otherwise, it indicates the error was not a panic. ```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); } } ``` -------------------------------- ### Create Route with GET Method Guard Source: https://docs.rs/actix-web/4.11.0/actix_web/web/fn.method.html Use `web::method` to specify the HTTP method for a route. This example sets up a GET request handler for a route with a project ID parameter. ```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())) ); ``` -------------------------------- ### ResourceDef Initialization and Basic Usage Source: https://docs.rs/actix-web/4.11.0/actix_web/dev/struct.ResourceDef.html Demonstrates how to initialize ResourceDef with different patterns and perform basic checks. ```APIDOC ## ResourceDef Initialization and Basic Usage ### Description This section covers the initialization of `ResourceDef` with various patterns and demonstrates basic usage examples. ### Method N/A (Constructor/Initialization) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ## ResourceDef::root_prefix ### Description Creates a `ResourceDef` with a root prefix. ### Method Associated Function ### Endpoint N/A ### Parameters - **prefix** (string) - The root prefix for the resource. ### Request Example ```rust use actix_router::ResourceDef; let resource = ResourceDef::root_prefix("user/{id}"); ``` ### Response - **ResourceDef** - A new `ResourceDef` instance. ## ResourceDef::prefix ### Description Creates a `ResourceDef` that is a prefix. ### Method Associated Function ### Endpoint N/A ### Parameters - **prefix** (string) - The prefix string for the resource. ### Request Example ```rust use actix_router::ResourceDef; let resource = ResourceDef::prefix("/user"); ``` ### Response - **ResourceDef** - A new `ResourceDef` instance. ## ResourceDef::new ### Description Creates a new `ResourceDef` with the given pattern(s). ### Method Associated Function ### Endpoint N/A ### Parameters - **patterns** (string or array of strings) - The pattern(s) for the resource. ### Request Example ```rust use actix_router::ResourceDef; let resource_single = ResourceDef::new("/user/{id}"); let resource_multiple = ResourceDef::new(["/profile", "/user/{id}"]); ``` ### Response - **ResourceDef** - A new `ResourceDef` instance. ## ResourceDef::is_match ### Description Checks if a given path matches the resource definition. ### Method `is_match` ### Endpoint N/A ### Parameters - **path** (string) - The path to check for a match. ### Request Example ```rust use actix_router::ResourceDef; let resource = ResourceDef::new("/user/{user_id}"); assert!(resource.is_match("/user/123")); ``` ### Response - **bool** - `true` if the path matches, `false` otherwise. ## ResourceDef::find_match ### Description Tries to match a path to the resource, returning the position where the match ends. ### Method `find_match` ### Endpoint N/A ### Parameters - **path** (string) - The path to match. ### Request Example ```rust let resource = ResourceDef::new("/user/{user_id}"); assert_eq!(resource.find_match("/user/123"), Some(10)); // Example value, actual might differ ``` ### Response - **Option** - The position where the match ends, or `None` if no match. ``` -------------------------------- ### Example: One to Many (Bind) Source: https://docs.rs/actix-web/4.11.0/actix_web/rt/net/struct.UdpSocket.html Demonstrates how to use `bind` to create a UDP echo server that can send and receive data 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); } } ``` ``` -------------------------------- ### Create an AllGuard with GET method and specific header Source: https://docs.rs/actix-web/4.11.0/actix_web/guard/fn.All.html This example demonstrates how to use `guard::All` to create a guard that matches only if the request method is GET and the 'accept' header has the value 'text/plain'. ```rust use actix_web::{guard, web, HttpResponse}; web::route() .guard( guard::All(guard::Get()) .and(guard::Header("accept", "text/plain")) ) .to(|| HttpResponse::Ok()); ``` -------------------------------- ### Get Next Weekday Source: https://docs.rs/actix-web/4.11.0/actix_web/cookie/time/enum.Weekday.html Returns the next weekday. Example shows Monday.next() returning Tuesday. ```rust assert_eq!(Weekday::Monday.next(), Weekday::Tuesday); ``` -------------------------------- ### Test Service Initialization and Request Handling Source: https://docs.rs/actix-web/4.11.0/actix_web/test/fn.init_service.html This example demonstrates how to initialize a service using `test::init_service` and then make a request to it. It asserts that the response status code is OK. ```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); } ``` -------------------------------- ### WebService Creation and Configuration Source: https://docs.rs/actix-web/4.11.0/src/actix_web/service.rs.html Demonstrates how to create a new `WebService`, set its name, add guards, and finish the service definition. ```APIDOC ## WebService API ### Description Provides methods to create, configure, and finalize a web service definition. ### Methods #### `WebService::new(path)` - **Description**: Creates a new `WebService` instance with a given path. - **Parameters**: - `path` (T: IntoPatterns) - The path pattern for the service. #### `WebService::name(name)` - **Description**: Sets a name for the service, used for URL generation. - **Parameters**: - `name` (&str) - The desired name for the service. #### `WebService::guard(guard)` - **Description**: Adds a match guard to the web service. - **Parameters**: - `guard` (G: Guard + 'static) - The guard to add. #### `WebService::finish(service)` - **Description**: Finalizes the service definition and returns an `HttpServiceFactory`. - **Parameters**: - `service` (F: IntoServiceFactory) - The service implementation. ### Example Usage ```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) ); ``` ``` -------------------------------- ### Get Previous Weekday Source: https://docs.rs/actix-web/4.11.0/actix_web/cookie/time/enum.Weekday.html Returns the previous weekday. Example shows Tuesday.previous() returning Monday. ```rust assert_eq!(Weekday::Tuesday.previous(), Weekday::Monday); ``` -------------------------------- ### Get Uri Query String Source: https://docs.rs/actix-web/4.11.0/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 let uri: Uri = "abc://username:password@example.com:123/path/data?key=value&key2=value2#fragid1".parse().unwrap(); assert_eq!(uri.query(), Some("key=value&key2=value2")); ``` -------------------------------- ### Create a Basic Cookie Source: https://docs.rs/actix-web/4.11.0/actix_web/cookie/struct.CookieBuilder.html A simple example demonstrating how to create a basic cookie with just a name and value using `Cookie::build()` and `finish()`. ```rust use cookie::Cookie; let c = Cookie::build("foo", "bar").finish(); assert_eq!(c.name_value(), ("foo", "bar")); ``` -------------------------------- ### HttpServer Creation and Basic Usage Source: https://docs.rs/actix-web/4.11.0/actix_web/struct.HttpServer.html Demonstrates how to create a new HttpServer instance with an application factory and bind it to an address. This is the fundamental way to start an actix-web server. ```APIDOC ## HttpServer::new() ### Description Creates a new HTTP server with the provided application factory. ### Method `HttpServer::new(factory: F)` ### Parameters - **factory** (Fn() -> I + Send + Clone + 'static) - The application factory function that will be used to create the application for each worker. ### Request Example ```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))? // Example of binding .run() .await } ``` ### Response - **Self** - Returns a new `HttpServer` instance. ``` -------------------------------- ### Example: Resume panic from JoinError Source: https://docs.rs/actix-web/4.11.0/actix_web/rt/task/struct.JoinError.html This example shows how to safely handle a panic from a spawned task. It 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()); } } ``` -------------------------------- ### Middleware Ordering Example Source: https://docs.rs/actix-web/4.11.0/src/actix_web/middleware/mod.rs.html Illustrates the nested structure of middleware services, showing how `MiddlewareC` wraps `MiddlewareB`, which in turn wraps `MiddlewareA`. ```plain MiddlewareCService { next: MiddlewareBService { next: MiddlewareAService { ... } } } ``` -------------------------------- ### Not Guard Usage Source: https://docs.rs/actix-web/4.11.0/actix_web/guard/struct.Not.html This example demonstrates how to use the `Not` guard to create a route that matches any HTTP method except GET. ```APIDOC ## POST /api/users ### Description Wraps a guard and inverts the outcome of its `Guard` implementation. The handler below will be called for any request method apart from `GET`. ### Method GET, POST, PUT, DELETE, etc. (Any method except GET) ### Endpoint / ### Parameters #### Query Parameters - **param1** (string) - Optional - Description of param1 ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (200) - **field1** (string) - Description of field1 #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### String Extractor Example Source: https://docs.rs/actix-web/4.11.0/actix_web/trait.FromRequest.html An example of using the built-in String extractor to get text data from a request's body. The extractor automatically decodes the body based on the request's charset. Use PayloadConfig for configuration. ```rust use actix_web::{post, web, FromRequest}; // extract text data from request #[post("/")] async fn index(text: String) -> String { format!("Body {}!", text) } ``` -------------------------------- ### Concurrent Read and Write Example Source: https://docs.rs/actix-web/4.11.0/actix_web/rt/net/struct.UnixStream.html Demonstrates how to concurrently read from and write to a Unix stream on the same task using the `ready` method. It handles potential `WouldBlock` errors and checks for readiness states. ```rust use tokio::io::Interest; use tokio::net::UnixStream; use std::error::Error; use std::io; #[tokio::main] async fn main() -> Result<(), Box> { let dir = tempfile::tempdir().unwrap(); let bind_path = dir.path().join("bind_path"); let stream = UnixStream::connect(bind_path).await?; loop { let ready = stream.ready(Interest::READABLE | Interest::WRITABLE).await?; if ready.is_readable() { let mut data = vec![0; 1024]; // Try to read data, this may still fail with `WouldBlock` // if the readiness event is a false positive. match stream.try_read(&mut data) { Ok(n) => { println!("read {} bytes", n); } Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { continue; } Err(e) => { return Err(e.into()); } } } if ready.is_writable() { // Try to write data, this may still fail with `WouldBlock` // if the readiness event is a false positive. match stream.try_write(b"hello world") { Ok(n) => { println!("write {} bytes", n); } Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { continue; } Err(e) => { return Err(e.into()); } } } } } ``` -------------------------------- ### User Authentication API Source: https://docs.rs/actix-web/4.11.0/actix_web/web/fn.resource.html Example of defining routes for a resource, including GET and HEAD methods, with a specific path pattern. ```APIDOC ## User Authentication API ### Description This example demonstrates how to define routes for a resource using `web::resource` and `route` methods. It includes handling GET requests and specifying a fallback for other methods like HEAD. ### Method GET, HEAD ### Endpoint /users/{userid}/{friend} ### Parameters #### Path Parameters - **userid** (string) - Required - The identifier for the user. - **friend** (string) - Required - The identifier for the friend. ### Request Example ```json { "example": "No request body needed for GET or HEAD" } ``` ### Response #### Success Response (200) - **HttpResponse** - Returns an OK response for GET requests. #### Error Response (405) - **HttpResponse** - Returns a MethodNotAllowed response for HEAD requests (as per the example). #### Response Example ```json { "example": "HttpResponse::Ok() for GET, HttpResponse::MethodNotAllowed() for HEAD" } ``` ``` -------------------------------- ### Serving Pre-compressed Gzip File Source: https://docs.rs/actix-web/4.11.0/actix_web/middleware/struct.Compress.html This example demonstrates how to serve a pre-compressed Gzip file from disk while correctly configuring headers to bypass middleware compression and inform the client. ```APIDOC ## Serving Pre-compressed Gzip File ### Description This example shows how to serve a pre-compressed Gzip file from disk. It configures the `Content-Encoding` header to `Gzip` to signal to the client that the content is already compressed and bypasses the `Compress` middleware for this specific response. ### Method N/A (Handler Function) ### Endpoint N/A (Handler Function) ### Parameters #### Path Parameters - `"./assets/index.html.gz"` (string) - Required - Path to the pre-compressed file. ### Request Body N/A ### Response - `HttpResponse` - The pre-compressed file content with appropriate headers. ### Request Example ```rust use actix_web::{middleware, http::header, web, App, HttpResponse, Responder}; async fn index_handler() -> actix_web::Result { Ok(actix_files::NamedFile::open_async("./assets/index.html.gz").await? .customize() .insert_header(header::ContentEncoding::Gzip)) } let app = App::new() .wrap(middleware::Compress::default()) .default_service(web::to(index_handler)); ``` ``` -------------------------------- ### Try to Get Current System Source: https://docs.rs/actix-web/4.11.0/actix_web/rt/struct.System.html Attempts to retrieve the current system without panicking. Returns None if no system is started. ```rust pub fn try_current() -> Option ``` -------------------------------- ### Server Build and Configuration Source: https://docs.rs/actix-web/4.11.0/actix_web/dev/struct.Server.html Demonstrates how to build and configure a new actix-web server instance. ```APIDOC ## POST /api/users ### Description Creates a new user in the system. ### Method POST ### Endpoint /api/users ### Parameters #### Request Body - **username** (string) - Required - The desired username for the new user. - **email** (string) - Required - The email address for the new user. - **password** (string) - Required - The password for the new user. ### Request Example ```json { "username": "johndoe", "email": "john.doe@example.com", "password": "securepassword123" } ``` ### 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": "johndoe", "email": "john.doe@example.com" } ``` ``` -------------------------------- ### Test Resource Map Setup and Basic Checks Source: https://docs.rs/actix-web/4.11.0/src/actix_web/rmap.rs.html Sets up a sample resource map with nested routes and performs basic sanity checks using `has_resource` to verify that existing and non-existing paths are correctly identified. ```rust let mut root = ResourceMap::new(ResourceDef::root_prefix("")); let mut user_map = ResourceMap::new(ResourceDef::root_prefix("/user/{id}")); user_map.add(&mut ResourceDef::new("/"), None); user_map.add(&mut ResourceDef::new("/profile"), None); user_map.add(&mut ResourceDef::new("/article/{id}"), None); user_map.add(&mut ResourceDef::new("/post/{post_id}"), None); user_map.add( &mut ResourceDef::new("/post/{post_id}/comment/{comment_id}"), None, ); root.add(&mut ResourceDef::new("/info"), None); root.add(&mut ResourceDef::new("/v{version:[[:digit:]]{1}}"), None); root.add( &mut ResourceDef::root_prefix("/user/{id}"), Some(Rc::new(user_map)), ); root.add(&mut ResourceDef::new("/info"), None); let root = Rc::new(root); ResourceMap::finish(&root); // sanity check resource map setup assert!(root.has_resource("/info")); assert!(!root.has_resource("/bar")); assert!(root.has_resource("/v1")); assert!(root.has_resource("/v2")); assert!(!root.has_resource("/v33")); assert!(!root.has_resource("/user/22")); assert!(root.has_resource("/user/22/")); assert!(root.has_resource("/user/22/profile")); // extract patterns from paths ``` -------------------------------- ### Get Monday Week Number Source: https://docs.rs/actix-web/4.11.0/actix_web/cookie/time/parsing/struct.Parsed.html Retrieves the parsed week number, where the week starts on Monday. Returns `None` if not present. ```rust pub const fn monday_week_number(&self) -> Option ``` -------------------------------- ### ResourceDef Matching Examples Source: https://docs.rs/actix-web/4.11.0/actix_web/dev/struct.ResourceDef.html Demonstrates how to create and use ResourceDef for matching static, prefixed, and dynamic URL patterns. ```APIDOC ## ResourceDef Matching Examples ### Description Examples of creating and using `ResourceDef` for matching static, prefixed, and dynamic URL patterns. ### Method N/A (Illustrative examples) ### Endpoint N/A ### Parameters N/A ### Request Example ```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)); ``` ### Response N/A ``` -------------------------------- ### Get Sunday Week Number Source: https://docs.rs/actix-web/4.11.0/actix_web/cookie/time/parsing/struct.Parsed.html Retrieves the parsed week number, where the week starts on Sunday. Returns `None` if not present. ```rust pub const fn sunday_week_number(&self) -> Option ``` -------------------------------- ### Get Monday-Based Week Number Source: https://docs.rs/actix-web/4.11.0/actix_web/cookie/time/struct.PrimitiveDateTime.html Retrieve the week number (0-53) where week 1 starts on the first Monday, from a PrimitiveDateTime. ```rust assert_eq!(datetime!(2019-01-01 0:00).monday_based_week(), 0); assert_eq!(datetime!(2020-01-01 0:00).monday_based_week(), 0); assert_eq!(datetime!(2020-12-31 0:00).monday_based_week(), 52); assert_eq!(datetime!(2021-01-01 0:00).monday_based_week(), 0); ``` -------------------------------- ### System::new() Source: https://docs.rs/actix-web/4.11.0/actix_web/rt/struct.System.html Creates a new System instance. This method will panic if the underlying Tokio runtime cannot be created. ```APIDOC ## pub fn new() -> SystemRunner ### Description Create a new system. ### Panics Panics if underlying Tokio runtime can not be created. ### Source ```rust pub fn new() -> SystemRunner ``` ``` -------------------------------- ### Quality Value Examples Source: https://docs.rs/actix-web/4.11.0/actix_web/http/header/struct.Quality.html Demonstrates the usage of the `q` function and `Quality` constants for creating and comparing quality values. Includes examples for maximum, default, and specific float values. ```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"); ``` -------------------------------- ### Get Sunday-Based Week Number Source: https://docs.rs/actix-web/4.11.0/actix_web/cookie/time/struct.PrimitiveDateTime.html Retrieve the week number (0-53) where week 1 starts on the first Sunday, from a PrimitiveDateTime. ```rust assert_eq!(datetime!(2019-01-01 0:00).sunday_based_week(), 0); assert_eq!(datetime!(2020-01-01 0:00).sunday_based_week(), 0); assert_eq!(datetime!(2020-12-31 0:00).sunday_based_week(), 52); assert_eq!(datetime!(2021-01-01 0:00).sunday_based_week(), 0); ``` -------------------------------- ### Defining a Basic Resource Source: https://docs.rs/actix-web/4.11.0/src/actix_web/resource.rs.html Demonstrates how to define a simple resource with a GET route that returns a 'hello' string. ```rust fn my_resource_1() -> Resource { web::resource("/test1").route(web::get().to(|| async { "hello" })) } ``` -------------------------------- ### Ready Methods Source: https://docs.rs/actix-web/4.11.0/actix_web/rt/net/struct.Ready.html Methods for checking the readiness state of an I/O resource. ```APIDOC ### `impl Ready` Methods #### `is_empty(self) -> bool` Returns true if `Ready` is the empty set. ##### Examples ```rust use tokio::io::Ready; assert!(Ready::EMPTY.is_empty()); assert!(!Ready::READABLE.is_empty()); ``` #### `is_readable(self) -> bool` Returns `true` if the value includes `readable`. ##### Examples ```rust use tokio::io::Ready; assert!(!Ready::EMPTY.is_readable()); assert!(Ready::READABLE.is_readable()); assert!(Ready::READ_CLOSED.is_readable()); assert!(!Ready::WRITABLE.is_readable()); ``` #### `is_writable(self) -> bool` Returns `true` if the value includes writable `readiness`. ##### Examples ```rust use tokio::io::Ready; assert!(!Ready::EMPTY.is_writable()); assert!(!Ready::READABLE.is_writable()); assert!(Ready::WRITABLE.is_writable()); assert!(Ready::WRITE_CLOSED.is_writable()); ``` #### `is_read_closed(self) -> bool` Returns `true` if the value includes read-closed `readiness`. ##### Examples ```rust use tokio::io::Ready; assert!(!Ready::EMPTY.is_read_closed()); assert!(!Ready::READABLE.is_read_closed()); assert!(Ready::READ_CLOSED.is_read_closed()); ``` #### `is_write_closed(self) -> bool` Returns `true` if the value includes write-closed `readiness`. ##### Examples ```rust use tokio::io::Ready; assert!(!Ready::EMPTY.is_write_closed()); assert!(!Ready::WRITABLE.is_write_closed()); assert!(Ready::WRITE_CLOSED.is_write_closed()); ``` #### `is_priority(self) -> bool` Returns `true` if the value includes priority `readiness`. ##### Examples ```rust use tokio::io::Ready; assert!(!Ready::EMPTY.is_priority()); assert!(!Ready::WRITABLE.is_priority()); assert!(Ready::PRIORITY.is_priority()); ``` #### `is_error(self) -> bool` Returns `true` if the value includes error `readiness`. ##### Examples ```rust use tokio::io::Ready; assert!(!Ready::EMPTY.is_error()); assert!(!Ready::WRITABLE.is_error()); assert!(Ready::ERROR.is_error()); ``` ``` -------------------------------- ### Get Monday-Based Week Number from UtcDateTime Source: https://docs.rs/actix-web/4.11.0/actix_web/cookie/time/struct.UtcDateTime.html Calculates the week number where week 1 starts on a Monday. The range is 0 to 53. ```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); ``` -------------------------------- ### Get Sunday-Based Week Number from UtcDateTime Source: https://docs.rs/actix-web/4.11.0/actix_web/cookie/time/struct.UtcDateTime.html Calculates the week number where week 1 starts on a Sunday. The range is 0 to 53. ```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); ``` -------------------------------- ### System::with_tokio_rt() Source: https://docs.rs/actix-web/4.11.0/actix_web/rt/struct.System.html Creates a new System instance using a provided Tokio Runtime factory closure. ```APIDOC ## pub fn with_tokio_rt(runtime_factory: F) -> SystemRunner where F: FnOnce() -> Runtime, ### Description Create a new System using the Tokio Runtime returned from a closure. ### Source ```rust pub fn with_tokio_rt(runtime_factory: F) -> SystemRunner where F: FnOnce() -> Runtime, ``` ``` -------------------------------- ### Service Usage Example Source: https://docs.rs/actix-web/4.11.0/actix_web/dev/trait.Service.html Illustrates how to use the Service trait, including implementing it for a custom struct and using `fn_service` for functions. ```APIDOC ### Example Usage ```rust struct MyService; impl Service for MyService { type Response = u64; type Error = MyError; type Future = Pin>>>; fn poll_ready(&self, cx: &mut Context<'_>) -> Poll> { ... } fn call(&self, req: u8) -> Self::Future { ... } } // Alternatively, using fn_service for functions: async fn my_service(req: u8) -> Result; let svc = fn_service(my_service); svc.call(123); ``` ``` -------------------------------- ### Get Month Source: https://docs.rs/actix-web/4.11.0/actix_web/cookie/time/struct.OffsetDateTime.html Retrieves the month from a DateTime object, adjusted for its stored offset. The second example illustrates how crossing a timezone boundary can affect the month. ```rust assert_eq!(datetime!(2019-01-01 0:00 UTC).month(), Month::January); assert_eq!( datetime!(2019-12-31 23:00 UTC) .to_offset(offset!(+1)) .month(), Month::January, ); ``` -------------------------------- ### Setting and Extracting Data Example Source: https://docs.rs/actix-web/4.11.0/actix_web/web/struct.Data.html Example demonstrating how to set application data using `app_data` and extract it within a handler using `Data` or `HttpRequest::app_data`. ```APIDOC ## Examples ```rust use std::sync::Mutex; use actix_web::{App, HttpRequest, HttpResponse, Responder, web::{self, Data}}; struct MyData { counter: usize, } /// Use the `Data` extractor to access data in a handler. async fn index(data: Data>) -> impl Responder { let mut my_data = data.lock().unwrap(); my_data.counter += 1; HttpResponse::Ok() } /// Alternatively, use the `HttpRequest::app_data` method to access data in a handler. async fn index_alt(req: HttpRequest) -> impl Responder { let data = req.app_data::>>().unwrap(); let mut my_data = data.lock().unwrap(); my_data.counter += 1; HttpResponse::Ok() } let data = Data::new(Mutex::new(MyData { counter: 0 })); let app = App::new() // Store `MyData` in application storage. .app_data(Data::clone(&data)) .route("/index.html", web::get().to(index)) .route("/index-alt.html", web::get().to(index_alt)); ``` ``` -------------------------------- ### Get Year Source: https://docs.rs/actix-web/4.11.0/actix_web/cookie/time/struct.OffsetDateTime.html Retrieves the year from a DateTime object, adjusted for its stored offset. The second example shows how crossing a timezone boundary can change the year. ```rust assert_eq!(datetime!(2019-01-01 0:00 UTC).year(), 2019); assert_eq!( datetime!(2019-12-31 23:00 UTC) .to_offset(offset!(+1)) .year(), 2020, ); assert_eq!(datetime!(2020-01-01 0:00 UTC).year(), 2020); ``` -------------------------------- ### Create a Basic Resource with GET and POST Handlers Source: https://docs.rs/actix-web/4.11.0/actix_web/struct.Resource.html Defines a resource at the root path and associates GET and POST HTTP methods with simple response handlers. ```rust use actix_web::{web, App, HttpResponse}; let app = App::new().service( web::resource("/") .get(|| HttpResponse::Ok()) .post(|| async { "Hello World!" }) ); ``` -------------------------------- ### Get Day Number From Sunday (Zero-Indexed) Source: https://docs.rs/actix-web/4.11.0/actix_web/cookie/time/enum.Weekday.html Returns the zero-indexed number of the day of the week, where Sunday is 0. Example shows Monday returning 1. ```rust assert_eq!(Weekday::Monday.number_days_from_sunday(), 1); ``` -------------------------------- ### TRACE /{project_id} Source: https://docs.rs/actix-web/4.11.0/actix_web/web/fn.trace.html Example of setting up a TRACE route for a specific project ID. ```APIDOC ## POST /api/users ### Description Creates a new user in the system. ### Method POST ### Endpoint /api/users ### Parameters #### Query Parameters - **limit** (integer) - Optional - The maximum number of users to return. #### 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** (integer) - 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": 123, "username": "john_doe", "email": "john.doe@example.com" } ``` ``` -------------------------------- ### Get Day Number From Monday (Zero-Indexed) Source: https://docs.rs/actix-web/4.11.0/actix_web/cookie/time/enum.Weekday.html Returns the zero-indexed number of the day of the week, where Monday is 0. Example shows Monday returning 0. ```rust assert_eq!(Weekday::Monday.number_days_from_monday(), 0); ``` -------------------------------- ### Get Day Number From Sunday (One-Indexed) Source: https://docs.rs/actix-web/4.11.0/actix_web/cookie/time/enum.Weekday.html Returns the one-indexed number of the day of the week, where Sunday is 1. Example shows Monday returning 2. ```rust assert_eq!(Weekday::Monday.number_from_sunday(), 2); ``` -------------------------------- ### Example: One to One (Connect) Source: https://docs.rs/actix-web/4.11.0/actix_web/rt/net/struct.UdpSocket.html Illustrates using `connect` to associate a UdpSocket with a single remote address, allowing communication via `send` and `recv`. ```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); } } ``` ``` -------------------------------- ### Initialize and Add Cookies to CookieJar Source: https://docs.rs/actix-web/4.11.0/actix_web/cookie/struct.CookieJar.html Demonstrates how to create a new CookieJar and add initial cookies using `add_original`. ```rust use cookie::{Cookie, CookieJar}; let mut jar = CookieJar::new(); jar.add_original(Cookie::new("name", "value")); jar.add_original(Cookie::new("second", "another")); ``` -------------------------------- ### Get Day Number From Monday (One-Indexed) Source: https://docs.rs/actix-web/4.11.0/actix_web/cookie/time/enum.Weekday.html Returns the one-indexed number of the day of the week, where Monday is 1. Example shows Monday returning 1. ```rust assert_eq!(Weekday::Monday.number_from_monday(), 1); ``` -------------------------------- ### Create new WebService instance Source: https://docs.rs/actix-web/4.11.0/src/actix_web/service.rs.html Initializes a `WebService` with a given path definition. Used for defining the routing path for a service. ```rust pub fn new(path: T) -> Self { WebService { rdef: path.patterns(), name: None, guards: Vec::new(), } } ```