### Basic Router Usage Example Source: https://docs.rs/rouille/3.6.2/rouille/macro.router.html Demonstrates the fundamental usage of the router macro with simple GET requests and literal paths. ```rust let _result = router!(request, // first route (GET) (/) => { 12 }, // second route (GET) (/hello) => { 43 * 7 }, // ... other routes here ... // default route _ => 5 ); ``` -------------------------------- ### Initialize Websocket Connection Source: https://docs.rs/rouille/3.6.2/rouille/websocket/index.html Use this function to start a websocket connection. It returns a `Response` to be sent to the client and a `Receiver` for the websocket. Ensure the subprotocol matches the client's request or pass `None` if subprotocols are not critical. This example also shows how to store the websocket receiver for later use. ```rust use std::sync::Mutex; use std::sync::mpsc::Receiver; use rouille::Request; use rouille::Response; use rouille::websocket; fn handle_request(request: &Request, websockets: &Mutex>>) -> Response { let (response, websocket) = try_or_400!(websocket::start(request, Some("my-subprotocol"))); websockets.lock().unwrap().push(websocket); response } ``` -------------------------------- ### Start a Rouille Server Source: https://docs.rs/rouille/3.6.2/rouille/index.html This snippet demonstrates how to start an HTTP server using Rouille. The server listens on the specified address and executes the provided closure for each incoming request. The closure must return a `Response` object. ```rust use rouille::Request; use rouille::Response; rouille::start_server("0.0.0.0:80", move |request| { Response::text("hello world") }); ``` -------------------------------- ### Server Creation and Basic Usage Source: https://docs.rs/rouille/3.6.2/rouille/struct.Server.html Demonstrates how to create a new server instance, define a request handler, and start the server. ```APIDOC ## Server Creation and Basic Usage ### Description This section covers the creation of a `Server` instance using `Server::new` and provides a basic example of handling requests. ### Method `Server::new` ### Endpoint N/A (This is a library function, not an HTTP endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use rouille::Server; use rouille::Response; let server = Server::new("localhost:0", |request| { Response::text("hello world") }).unwrap(); println!("Listening on {:?}", server.server_addr()); server.run(); ``` ### Response #### Success Response (200) N/A (This function returns a `Result` indicating success or failure during server setup.) #### Response Example N/A ``` -------------------------------- ### start_server Source: https://docs.rs/rouille Initializes and starts an HTTP server that listens on a specified address and processes incoming requests using a provided handler closure. ```APIDOC ## start_server ### Description Starts a server that listens on the specified address. For every incoming request, the provided closure is executed to generate a response. ### Parameters - **address** (string) - Required - The address and port to bind the server to (e.g., "0.0.0.0:80"). - **handler** (closure) - Required - A function or closure that takes a `Request` object and returns a `Response` object. ### Request Example rouille::start_server("0.0.0.0:80", move |request| { Response::text("hello world") }); ``` -------------------------------- ### Start a Rouille Server Source: https://docs.rs/rouille/3.6.2/rouille/fn.start_server.html Starts a server with a given address and request handler. The handler must be thread-safe and capture its environment by value. ```rust pub fn start_server(addr: A, handler: F) -> ! where A: ToSocketAddrs, F: Send + Sync + 'static + Fn(&Request) -> Response, ``` -------------------------------- ### start_server_with_pool Source: https://docs.rs/rouille/3.6.2/rouille/fn.start_server_with_pool.html Starts an HTTP server with a specified thread pool size. If pool_size is None, it defaults to 8 * num-cpus. Panics if pool_size is zero. ```APIDOC ## start_server_with_pool ### Description Identical to `start_server` but uses a `ThreadPool` of the given size. When `pool_size` is `None`, the thread pool size will default to `8 * num-cpus`. `pool_size` must be greater than zero or this function will panic. ### Method POST (or relevant HTTP method for server start) ### Endpoint Not applicable (this is a function call, not a REST endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust // Example usage within a Rust application rouille::start_server_with_pool("127.0.0.1:8080", Some(4), move |request| { // Request handling logic here rouille::Response::text("Hello world!") }); ``` ### Response #### Success Response (200) This function does not return a value in the traditional sense; it runs indefinitely until the server is stopped or panics. #### Response Example None ``` -------------------------------- ### Start Websocket Connection Source: https://docs.rs/rouille/3.6.2/rouille/websocket/fn.start.html Initiates a websocket protocol connection. Requires a Request object and an optional subprotocol. ```rust pub fn start( request: &Request, subprotocol: Option, ) -> Result<(Response, Receiver), WebsocketError> where S: Into>, ``` -------------------------------- ### accept Macro with Default Handler Source: https://docs.rs/rouille/3.6.2/rouille/macro.accept.html Example of using the */* wildcard to provide a default response when no other MIME types match. ```rust use rouille::Request; use rouille::Response; fn handle(request: &Request) -> Response { accept!(request, "text/html" => Response::html("

Hello world

"), "text/plain" => Response::text("Hello world"), "*/*" => Response::empty_406() ) } ``` -------------------------------- ### Create and Run a Basic Rouille Server Source: https://docs.rs/rouille/3.6.2/rouille/struct.Server.html Use `Server::new` to create a server instance with a given address and handler. The server starts listening immediately. The handler closure processes incoming requests and returns a `Response`. ```rust use rouille::Server; use rouille::Response; let server = Server::new("localhost:0", |request| { Response::text("hello world") }).unwrap(); println!("Listening on {:?}", server.server_addr()); server.run(); ``` -------------------------------- ### Use find_route for request handling Source: https://docs.rs/rouille/3.6.2/rouille/macro.find_route.html Example demonstrating how to chain multiple request handlers using the find_route macro. ```rust use rouille::{Request, Response}; fn handle_request_a(_: &Request) -> Response { // ... } fn handle_request_b(_: &Request) -> Response { // ... } fn handle_request_c(_: &Request) -> Response { // ... } // First calls `handle_request_a`. If it returns anything else than a 404 error, then the // `response` will contain the return value. // // Instead if `handle_request_a` returned a 404 error, then `handle_request_b` is tried. // If `handle_request_b` also returns a 404 error, then `handle_request_c` is tried. let response = find_route!( handle_request_a(request), handle_request_b(request), handle_request_c(request) ); ``` -------------------------------- ### Basic accept Macro Usage Source: https://docs.rs/rouille/3.6.2/rouille/macro.accept.html Example of using the accept macro to return different responses based on the request's Accept header. ```rust use rouille::Request; use rouille::Response; fn handle(request: &Request) -> Response { accept!(request, "text/html" => Response::html("

Hello world

"), "text/plain" => Response::text("Hello world"), ) } ``` -------------------------------- ### Log Request Example Source: https://docs.rs/rouille/3.6.2/rouille/fn.log.html Demonstrates using rouille::log to output request information to standard output while returning a response. ```rust use std::io; use rouille::{Request, Response}; fn handle(request: &Request) -> Response { rouille::log(request, io::stdout(), || { Response::text("hello world") }) } ``` -------------------------------- ### start_server Function Source: https://docs.rs/rouille/3.6.2/rouille/fn.start_server.html Starts a server and uses the given requests handler. The request handler takes a `&Request` and must return a `Response` to send to the user. For more control, see the `Server` struct. ```APIDOC ## start_server ### Description Starts a server and uses the given requests handler. The request handler takes a `&Request` and must return a `Response` to send to the user. > **Note** : `start_server` is meant to be an easy-to-use function. If you want more control, see the `Server` struct. ### Function Signature ```rust pub fn start_server(addr: A, handler: F) -> ! where A: ToSocketAddrs, F: Send + Sync + 'static + Fn(&Request) -> Response, ``` ### Common Mistakes - The handler must capture its environment by value and not by reference (`'static`). If you use closure, don’t forget to put `move` in front of the closure. - The handler must also be thread-safe (`Send` and `Sync`). For example, a handler that mutably accesses a counter from the outside is not thread-safe without synchronization primitives like `Mutex`. ### Panic Handling If your request handler panics, a 500 error will automatically be sent to the client. ### Panics This function will panic if the server starts to fail (for example if you use a port that is already occupied) or if the socket is force-closed by the operating system. If you need to handle these situations, please see `Server`. ``` -------------------------------- ### Get Request Method Source: https://docs.rs/rouille/3.6.2/rouille/struct.Request.html The `method` method returns the HTTP method of the request as a string slice (e.g., 'GET', 'POST'). ```rust pub fn method(&self) -> &str ``` -------------------------------- ### Handle Request with assert_or_400 Source: https://docs.rs/rouille/3.6.2/rouille/macro.assert_or_400.html Example of using `assert_or_400` within a request handler. Ensure `post_input!` and `try_or_400` are available in scope. ```rust use rouille::Request; use rouille::Response; fn handle_something(request: &Request) -> Response { let data = try_or_400!(post_input!(request, { field1: u32, field2: String, })); assert_or_400!(data.field1 >= 2); Response::text("hello") } ``` -------------------------------- ### Get GET Parameter Value Source: https://docs.rs/rouille/3.6.2/rouille/struct.Request.html The `get_param` method retrieves the value of a specified GET parameter from the URL. It returns `None` if the parameter does not exist. ```rust pub fn get_param(&self, param_name: &str) -> Option ``` -------------------------------- ### start_server_with_pool function signature Source: https://docs.rs/rouille/3.6.2/rouille/fn.start_server_with_pool.html Defines the function signature for starting a server with a thread pool. Requires a socket address, an optional pool size, and a request handler. ```rust pub fn start_server_with_pool( addr: A, pool_size: Option, handler: F, ) -> ! where A: ToSocketAddrs, F: Send + Sync + 'static + Fn(&Request) -> Response, ``` -------------------------------- ### Basic Iterator Methods Source: https://docs.rs/rouille/3.6.2/rouille/struct.HeadersIter.html Provides fundamental iterator methods for HeadersIter, including `next` to get the next item and `size_hint` for estimating remaining elements. ```rust fn next(&mut self) -> Option ``` ```rust fn size_hint(&self) -> (usize, Option) ``` -------------------------------- ### Start CGI Request Handling in Rouille Source: https://docs.rs/rouille/3.6.2/rouille/cgi/index.html Use this snippet to dispatch incoming requests to an external CGI process. Ensure the command is correctly specified and executable. The `.unwrap()` is generally safe as panics are converted to 500 errors. ```rust use std::process::Command; use rouille::cgi::CgiRun; rouille::start_server("localhost:8080", move |request| { Command::new("php-cgi").start_cgi(request).unwrap() }); ``` -------------------------------- ### Use try_or_400 in a request handler Source: https://docs.rs/rouille/3.6.2/rouille/macro.try_or_400.html Example of using the macro to handle input parsing errors within a function returning a Response. ```rust use rouille::Request; use rouille::Response; fn handle_something(request: &Request) -> Response { let data = try_or_400!(post_input!(request, { field1: u32, field2: String, })); Response::text("hello") } ``` -------------------------------- ### Rouille Handler with Mutex for Thread Safety Source: https://docs.rs/rouille/3.6.2/rouille/fn.start_server.html This example shows the correct way to handle requests by using a Mutex to safely increment a counter across multiple threads. ```rust use std::sync::Mutex; let requests_counter = Mutex::new(0); rouille::start_server("localhost:80", move |request| { *requests_counter.lock().unwrap() += 1; // rest of the handler }) ``` -------------------------------- ### websocket::start Source: https://docs.rs/rouille/3.6.2/rouille/websocket/index.html Initiates a websocket connection by returning a response and a receiver for the websocket object. ```APIDOC ## Function: websocket::start ### Description Builds a Response that initiates the websocket protocol. This function validates the request and returns an error if it is not a valid websocket initialization request. ### Parameters - **request** (Request) - Required - The incoming HTTP request. - **subprotocol** (Option<&str>) - Required - The subprotocol to use for the connection. Must match one requested by the client or be None. ### Response - **(Response, Receiver)** - Returns a tuple containing the HTTP response to send to the client and a receiver that will eventually contain the established Websocket object. ``` -------------------------------- ### GET /request/data Source: https://docs.rs/rouille/3.6.2/rouille/struct.Request.html Retrieves the body data from the incoming request. ```APIDOC ## GET /request/data ### Description Retrieves the body of the request as a stream of data. ### Method GET ### Response #### Success Response (200) - **data** (ResponseBody) - The body content of the request. ``` -------------------------------- ### GET /request/remote_addr Source: https://docs.rs/rouille/3.6.2/rouille/struct.Request.html Retrieves the socket address of the client that initiated the request. ```APIDOC ## GET /request/remote_addr ### Description Returns the address of the client that made this request. ### Method GET ### Response #### Success Response (200) - **remote_addr** (SocketAddr) - The IP address and port of the client. ``` -------------------------------- ### Running the Server Source: https://docs.rs/rouille/3.6.2/rouille/struct.Server.html Details on how to run the server indefinitely. ```APIDOC ## Running the Server ### Description Runs the server indefinitely, processing requests until the listening socket is closed by the operating system. ### Method `run` ### Endpoint N/A (This is a method on the `Server` struct.) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use rouille::Server; let server = Server::new("localhost:0", |_request| rouille::Response::text("hello")).unwrap(); server.run(); // This call will block indefinitely ``` ### Response #### Success Response (200) N/A (This method does not return a value upon successful execution; it runs the server.) #### Response Example N/A ``` -------------------------------- ### Server Address Retrieval Source: https://docs.rs/rouille/3.6.2/rouille/struct.Server.html How to get the network address the server is listening on. ```APIDOC ## Server Address Retrieval ### Description Retrieves the socket address that the server is currently listening on. ### Method `server_addr` ### Endpoint N/A (This is a method on the `Server` struct.) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use rouille::Server; let server = Server::new("localhost:0", |_request| rouille::Response::text("hello")).unwrap(); let addr = server.server_addr(); println!("Server listening on: {:?}", addr); ``` ### Response #### Success Response (200) - **SocketAddr** (SocketAddr) - The network address the server is listening on. #### Response Example ``` 127.0.0.1:12345 ``` ``` -------------------------------- ### Server Configuration Source: https://docs.rs/rouille/3.6.2/rouille/struct.Server.html Explains how to configure server settings like thread pool size. ```APIDOC ## Server Configuration ### Description This section details how to configure the server's thread pool size for processing requests. ### Method `pool_size` ### Endpoint N/A (This is a method on the `Server` struct.) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use rouille::Server; let server = Server::new("localhost:0", |_request| rouille::Response::text("hello")) .unwrap() .pool_size(10); ``` ### Response #### Success Response (200) N/A (This method returns `Self`, allowing for chaining.) #### Response Example N/A ``` -------------------------------- ### Get All Headers Source: https://docs.rs/rouille/3.6.2/rouille/struct.Request.html The `headers` method returns an iterator over all the headers present in the request. ```rust pub fn headers(&self) -> HeadersIter<'_> ``` -------------------------------- ### WebsocketError Enum Source: https://docs.rs/rouille/3.6.2/rouille/websocket/enum.WebsocketError.html Details the possible errors that can occur when attempting to start a websocket connection using the Rouille library. ```APIDOC ## Enum WebsocketError ### Description Error that can happen when attempting to start websocket. ### Variants #### InvalidWebsocketRequest The request does not match a websocket request. The conditions are: * The method must be `GET`. * The HTTP version must be at least 1.1. * The request must include `Host`. * The `Connection` header must include `websocket`. * The `Sec-WebSocket-Version` header must be `13`. * Must have a `Sec-WebSocket-Key` header. #### WrongSubprotocol The subprotocol passed to the function was not requested by the client. ### Trait Implementations #### impl Debug for WebsocketError ##### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. #### impl Display for WebsocketError ##### fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), Error> Formats the value using the given formatter. #### impl Error for WebsocketError ##### fn source(&self) -> Option<&(dyn Error + 'static)> Returns the lower-level source of this error, if any. ##### fn description(&self) -> &str Deprecated since 1.42.0: use the Display impl or to_string(). ##### fn cause(&self) -> Option<&dyn Error> Deprecated since 1.33.0: replaced by Error::source, which can support downcasting. ##### fn provide<'a>(&'a self, request: &mut Request<'a>) This is a nightly-only experimental API. (`error_generic_member_access`) Provides type-based access to context intended for error reports. ### Auto Trait Implementations * Freeze * RefUnwindSafe * Send * Sync * Unpin * UnwindSafe ### Blanket Implementations * impl Any for T * impl Borrow for T * impl BorrowMut for T * impl From for T * impl Into for T * impl ToString for T * impl TryFrom for T * impl TryInto for T * impl VZip for T * impl ErasedDestructor for T ``` -------------------------------- ### rouille::websocket::start Source: https://docs.rs/rouille/3.6.2/rouille/websocket/fn.start.html Initiates the websocket protocol by building a Response. ```APIDOC ## POST /websocket ### Description Builds a `Response` that initiates the websocket protocol. ### Method POST ### Endpoint /websocket ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **request** (`&Request`) - Required - The incoming HTTP request object. - **subprotocol** (`Option where S: Into>`) - Optional - The websocket subprotocol to use. ### Request Example ```json { "request": "", "subprotocol": "chat" } ``` ### Response #### Success Response (200) - **Response** (`Response`) - The HTTP response initiating the websocket connection. - **Receiver** (`Receiver`) - A receiver for websocket messages. #### Response Example ```json { "response": "", "receiver": "" } ``` ``` -------------------------------- ### fn take Source: https://docs.rs/rouille/3.6.2/rouille/input/multipart/struct.MultipartData.html Creates an adapter which will read at most a specified number of bytes from the MultipartData source. ```APIDOC ## fn take(self, limit: u64) -> Take ### Description Creates an adapter which will read at most `limit` bytes from the current data source. ### Parameters #### Request Body - **limit** (u64) - Required - The maximum number of bytes to read from the source. ``` -------------------------------- ### Trait: CgiRun Source: https://docs.rs/rouille/3.6.2/rouille/cgi/trait.CgiRun.html Documentation for the start_cgi method used to dispatch requests to a CGI process. ```APIDOC ## Trait: CgiRun ### Description Dispatches a request to a CGI process. This method modifies a Command to include necessary environment variables and the request body, executes the command, and waits for the child process to return response headers. ### Method fn start_cgi(self, request: &Request) -> Result ### Parameters - **self** (Command) - The command to be executed as a CGI process. - **request** (&Request) - The incoming HTTP request to be dispatched. ### Response - **Result** - Returns a Response object where the body holds a handle to the child process's stdout, or a CgiError if the execution fails. ``` -------------------------------- ### Create a Response from a File Source: https://docs.rs/rouille/3.6.2/rouille/struct.Response.html Use `Response::from_file` to serve the content of a file with a 200 OK status. Ensure the file is opened successfully and the correct content type is provided. ```rust use std::fs::File; use rouille::Response; let file = File::open("image.png").unwrap(); let response = Response::from_file("image/png", file); ``` -------------------------------- ### Get Specific Header Value Source: https://docs.rs/rouille/3.6.2/rouille/struct.Request.html The `header` method returns the value of a specific request header. It returns `None` if the header is not found. ```rust pub fn header(&self, key: &str) -> Option<&str> ``` -------------------------------- ### Get Raw URL Source: https://docs.rs/rouille/3.6.2/rouille/struct.Request.html The `raw_url` method returns the URL exactly as it was received from the client, including percent-encoded characters and the query string. ```rust pub fn raw_url(&self) -> &str ``` ```rust use rouille::Request; let request = Request::fake_http("GET", "/hello%20world?foo=bar", vec![], vec![]); assert_eq!(request.raw_url(), "/hello%20world?foo=bar"); ``` -------------------------------- ### Any Trait Implementation Source: https://docs.rs/rouille/3.6.2/rouille/input/post/struct.BufferedFile.html Provides a method to get the TypeId of a type, enabling runtime type identification. This is a blanket implementation for any type that is 'static. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### Parse HTTP Basic Authentication in Rust Source: https://docs.rs/rouille/3.6.2/rouille/input/fn.basic_http_auth.html Demonstrates how to use basic_http_auth to protect a route and return a login challenge if credentials are missing. ```rust use rouille::input; use rouille::Request; use rouille::Response; fn handle(request: &Request) -> Response { let auth = match input::basic_http_auth(request) { Some(a) => a, None => return Response::basic_http_auth_login_required("realm") }; if auth.login == "admin" && auth.password == "GT5GeKyLvKLxuc7mjF5h" { handle_after_login(request) } else { Response::text("Bad login/password").with_status_code(403) } } fn handle_after_login(request: &Request) -> Response { Response::text("You are in a secret area") } ``` -------------------------------- ### Get Client IP Address in Rouille Source: https://docs.rs/rouille/3.6.2/rouille/struct.Request.html Retrieves and formats the remote IP address of the client making the request. This is useful for logging or geo-location. ```rust use rouille::{Request, Response}; fn handle(request: &Request) -> Response { Response::text(format!("Your IP is: {:?}", request.remote_addr())) } ``` -------------------------------- ### Get Request Body Source: https://docs.rs/rouille/3.6.2/rouille/struct.Request.html The `data` method returns the request body as `Option>`. The body can only be retrieved once; subsequent calls will return `None`. ```rust pub fn data(&self) -> Option> ``` -------------------------------- ### Create a Response from Binary Data Source: https://docs.rs/rouille/3.6.2/rouille/struct.Response.html Use `Response::from_data` to build a 200 OK response with binary data. Specify the content type and the data as a byte vector. ```rust use rouille::Response; let response = Response::from_data("application/octet-stream", vec![1, 2, 3, 4]); ``` -------------------------------- ### Router with Path Parameters (Token-Style) Source: https://docs.rs/rouille/3.6.2/rouille/macro.router.html Shows how to define routes with path parameters using curly braces. Parameters are parsed via the `FromStr` trait. ```rust (GET) (/{id}/foo) => { ... }, ``` -------------------------------- ### Create an HTML Response Source: https://docs.rs/rouille/3.6.2/rouille/struct.Response.html Use `Response::html` to generate a response with HTML content. The content is provided as a string. ```rust use rouille::Response; let response = Response::html("

hello world

"); ``` -------------------------------- ### Iterator Adapters Source: https://docs.rs/rouille/3.6.2/rouille/struct.HeadersIter.html Demonstrates iterator adapters available for HeadersIter, including `step_by`, `chain`, `zip`, `intersperse`, `intersperse_with`, `map`, `for_each`, `filter`, `filter_map`, `enumerate`, `peekable`, and `skip_while`. ```rust fn step_by(self, step: usize) -> StepBy ``` ```rust fn chain(self, other: U) -> Chain::IntoIter> ``` ```rust fn zip(self, other: U) -> Zip::IntoIter> ``` ```rust fn intersperse(self, separator: Self::Item) -> Intersperse ``` ```rust fn intersperse_with(self, separator: G) -> IntersperseWith ``` ```rust fn map(self, f: F) -> Map ``` ```rust fn for_each(self, f: F) ``` ```rust fn filter

(self, predicate: P) -> Filter ``` ```rust fn filter_map(self, f: F) -> FilterMap ``` ```rust fn enumerate(self) -> Enumerate ``` ```rust fn peekable(self) -> Peekable ``` ```rust fn skip_while

(self, predicate: P) -> SkipWhile ``` -------------------------------- ### Rouille Handler with Request Counter (Incorrect) Source: https://docs.rs/rouille/3.6.2/rouille/fn.start_server.html This example demonstrates an incorrect way to handle requests by mutably accessing a counter from the outside, which is not thread-safe. ```rust let mut requests_counter = 0; rouille::start_server("localhost:80", move |request| { requests_counter += 1; // ... rest of the handler ... # panic!() }) ``` -------------------------------- ### TryInto Conversion Source: https://docs.rs/rouille/3.6.2/rouille/input/struct.CookiesIter.html Documentation for the try_into conversion method. ```APIDOC ## fn try_into(self) -> Result>::Error> ### Description Performs the conversion from the current type into the target type U. ### Parameters - **self** (T) - Required - The source object to convert. ``` -------------------------------- ### Error::cause Implementation for ProxyError (Deprecated) Source: https://docs.rs/rouille/3.6.2/rouille/proxy/enum.ProxyError.html Deprecated method for getting the underlying cause of the error. Use Error::source instead, which supports downcasting. ```rust fn cause(&self) -> Option<&dyn Error> ``` -------------------------------- ### Serve static assets with match_assets Source: https://docs.rs/rouille/3.6.2/rouille/fn.match_assets.html Basic usage of match_assets to serve files from a public directory. ```rust rouille::start_server("localhost:8000", move |request| { let response = rouille::match_assets(&request, "public"); if response.is_success() { return response; } // ... }); ``` -------------------------------- ### Error::description Implementation for ProxyError (Deprecated) Source: https://docs.rs/rouille/3.6.2/rouille/proxy/enum.ProxyError.html Deprecated method for getting a string description of the error. Prefer using the Display implementation or to_string() instead. ```rust fn description(&self) -> &str ``` -------------------------------- ### Get Decoded URL Source: https://docs.rs/rouille/3.6.2/rouille/struct.Request.html The `url` method returns the decoded URL, with percent-encoded characters resolved and the query string removed. Non-unicode characters are replaced with U+FFFD. ```rust pub fn url(&self) -> String ``` ```rust use rouille::Request; let request = Request::fake_http("GET", "/hello%20world?foo=bar", vec![], vec![]); assert_eq!(request.url(), "/hello world"); ``` -------------------------------- ### Serve static assets with a URL prefix Source: https://docs.rs/rouille/3.6.2/rouille/fn.match_assets.html Use remove_prefix on the request to serve static files under a specific URL path. ```rust rouille::start_server("localhost:8000", move |request| { if let Some(request) = request.remove_prefix("/static") { return rouille::match_assets(&request, "public"); } // ... }); ``` -------------------------------- ### Get Raw Query String Source: https://docs.rs/rouille/3.6.2/rouille/struct.Request.html The `raw_query_string` method returns the portion of the raw URL that comes after the first '?'. It returns an empty string if no query string is present. ```rust pub fn raw_query_string(&self) -> &str ``` -------------------------------- ### Any Trait Source: https://docs.rs/rouille/3.6.2/rouille/struct.Server.html Provides runtime type information. ```APIDOC ## Any Trait ### Description Provides runtime type information for trait objects. ### Methods #### `fn type_id(&self) -> TypeId` Gets the `TypeId` of `self`. ``` -------------------------------- ### Remove URL Prefix Source: https://docs.rs/rouille/3.6.2/rouille/struct.Request.html Use `remove_prefix` to create a new `Request` object with a specified prefix removed from its URL. Returns `None` if the URL does not start with the prefix. ```rust pub fn remove_prefix(&self, prefix: &str) -> Option ``` ```rust fn handle(request: &Request) -> Response { if let Some(request) = request.remove_prefix("/static") { return rouille::match_assets(&request, "/static"); } // ... } ``` -------------------------------- ### Dispatching requests based on host header Source: https://docs.rs/rouille/3.6.2/rouille/proxy/index.html Demonstrates using full_proxy to route requests to different backend servers based on the Host header. ```rust use rouille::{Request, Response}; use rouille::proxy; fn handle_request(request: &Request) -> Response { let config = match request.header("Host") { Some(h) if h == "domain1.com" => { proxy::ProxyConfig { addr: "domain1.handler.localnetwork", replace_host: None, } }, Some(h) if h == "domain2.com" => { proxy::ProxyConfig { addr: "domain2.handler.localnetwork", replace_host: None, } }, _ => return Response::empty_404() }; proxy::full_proxy(request, config).unwrap() } ``` -------------------------------- ### Router with String-Style Parameters Source: https://docs.rs/rouille/3.6.2/rouille/macro.router.html Shows how to use parameters within string-style URL definitions, requiring explicit `identity: type` pairs. ```rust (GET) ["/add/{a}/plus/{b}", a: u32, b: u32] => { let c = a + b; ... }, ``` -------------------------------- ### Multipart Implementations Source: https://docs.rs/rouille/3.6.2/rouille/input/multipart/struct.Multipart.html Details on the implementations and traits for the Multipart struct. ```APIDOC ## Implementations for Multipart<'a> ### `impl<'a> Freeze for Multipart<'a>` ### `impl<'a> !RefUnwindSafe for Multipart<'a>` ### `impl<'a> Send for Multipart<'a>` ### `impl<'a> !Sync for Multipart<'a>` ### `impl<'a> Unpin for Multipart<'a>` ### `impl<'a> !UnwindSafe for Multipart<'a>` ## Blanket Implementations ### `impl Any for T` #### `fn type_id(&self) -> TypeId` Gets the `TypeId` of `self`. ### `impl Borrow for T` #### `fn borrow(&self) -> &T` Immutably borrows from an owned value. ### `impl BorrowMut for T` #### `fn borrow_mut(&mut self) -> &mut T` Mutably borrows from an owned value. ### `impl From for T` #### `fn from(t: T) -> T` Returns the argument unchanged. ### `impl Into for T where U: From` #### `fn into(self) -> U` Calls `U::from(self)`. ### `impl TryFrom for T where U: Into` #### `type Error = Infallible` #### `fn try_from(value: U) -> Result>::Error>` Performs the conversion. ### `impl TryInto for T where U: TryFrom` #### `type Error = >::Error` #### `fn try_into(self) -> Result>::Error>` Performs the conversion. ### `impl VZip for T where V: MultiLane` #### `fn vzip(self) -> V` ### `impl ErasedDestructor for T where T: 'static` ``` -------------------------------- ### Create a Plain Text Response Source: https://docs.rs/rouille/3.6.2/rouille/struct.Response.html Use `Response::text` to create a response with plain text content. The text is provided as a string. ```rust use rouille::Response; let response = Response::text("hello world"); ``` -------------------------------- ### Session Implementations Source: https://docs.rs/rouille/3.6.2/rouille/session/struct.Session.html Details the implementations of methods for the Session struct. ```APIDOC ## Implementations for Session ### `impl<'r> Session<'r>` #### `pub fn client_has_sid(&self) -> bool` Returns true if the client gave us a session ID. If this returns false, then we are sure that no data is available. #### `pub fn id(&self) -> &str` Returns the id of the session. ``` -------------------------------- ### HeadersIter Trait Implementations Source: https://docs.rs/rouille/3.6.2/rouille/struct.HeadersIter.html Details the trait implementations for HeadersIter, including Clone, Debug, ExactSizeIterator, and Iterator. ```APIDOC ## Trait Implementations ### impl<'a> Clone for HeadersIter<'a> #### fn clone(&self) -> HeadersIter<'a> Returns a duplicate of the value. #### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. ### impl<'a> Debug for HeadersIter<'a> #### fn fmt(&self, f: &mut Formatter<'_>) -> Result Formats the value using the given formatter. ### impl<'a> ExactSizeIterator for HeadersIter<'a> #### fn len(&self) -> usize Returns the exact remaining length of the iterator. #### fn is_empty(&self) -> bool Returns `true` if the iterator is empty. ### impl<'a> Iterator for HeadersIter<'a> #### type Item = (&'a str, &'a str) The type of the elements being iterated over. #### fn next(&mut self) -> Option Advances the iterator and returns the next value. #### fn size_hint(&self) -> (usize, Option) Returns the bounds on the remaining length of the iterator. #### fn next_chunk(&mut self) -> Result<[Self::Item; N], IntoIter> Advances the iterator and returns an array containing the next `N` values. #### fn count(self) -> usize Consumes the iterator, counting the number of iterations and returning it. #### fn last(self) -> Option Consumes the iterator, returning the last element. #### fn advance_by(&mut self, n: usize) -> Result<(), NonZero> Advances the iterator by `n` elements. #### fn nth(&mut self, n: usize) -> Option Returns the `n`th element of the iterator. #### fn step_by(self, step: usize) -> StepBy Creates an iterator starting at the same point, but stepping by the given amount at each iteration. #### fn chain(self, other: U) -> Chain::IntoIter> Takes two iterators and creates a new iterator over both in sequence. #### fn zip(self, other: U) -> Zip::IntoIter> ‘Zips up’ two iterators into a single iterator of pairs. #### fn intersperse(self, separator: Self::Item) -> Intersperse Creates a new iterator which places a copy of `separator` between adjacent items of the original iterator. #### fn intersperse_with(self, separator: G) -> IntersperseWith Creates a new iterator which places an item generated by `separator` between adjacent items of the original iterator. #### fn map(self, f: F) -> Map Takes a closure and creates an iterator which calls that closure on each element. #### fn for_each(self, f: F) Calls a closure on each element of an iterator. #### fn filter

(self, predicate: P) -> Filter Creates an iterator which uses a closure to determine if an element should be yielded. #### fn filter_map(self, f: F) -> FilterMap Creates an iterator that both filters and maps. #### fn enumerate(self) -> Enumerate Creates an iterator which gives the current iteration count as well as the next value. #### fn peekable(self) -> Peekable Creates an iterator which can use the `peek` and `peek_mut` methods to look at the next element of the iterator without consuming it. #### fn skip_while

(self, predicate: P) -> SkipWhile Creates an iterator that `skip`s elements based on a predicate. ``` -------------------------------- ### Stoppable Server Source: https://docs.rs/rouille/3.6.2/rouille/struct.Server.html Creates a server that can be gracefully stopped. ```APIDOC ## Stoppable Server ### Description Starts the server in a new thread and returns a `JoinHandle` and a `Sender` for graceful shutdown. ### Method `stoppable` ### Endpoint N/A (This is a method on the `Server` struct.) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use rouille::Server; use std::thread; use std::time::Duration; let server = Server::new("localhost:0", |_request| rouille::Response::text("hello")).unwrap(); let (handle, sender) = server.stoppable(); // To stop the server later: sender.send(()).unwrap(); handle.join().unwrap(); ``` ### Response #### Success Response (200) - **(JoinHandle<()>, Sender<()>)** - A tuple containing a thread join handle and a sender for stopping the server. #### Response Example N/A ``` -------------------------------- ### Create a ResponseBody from a string Source: https://docs.rs/rouille/3.6.2/rouille/struct.ResponseBody.html Use this constructor to create a response body from a UTF-8 string. ```rust use rouille::ResponseBody; let body = ResponseBody::from_string("hello world"); ``` -------------------------------- ### Create a Permanent Redirect Response (301) Source: https://docs.rs/rouille/3.6.2/rouille/struct.Response.html Builds a Response with a 301 status code for permanent redirection. Use 303 if unsure about the best status code. ```rust use rouille::Response; let response = Response::redirect_301("/foo"); ``` -------------------------------- ### Router with Typed Path Parameters (Token-Style) Source: https://docs.rs/rouille/3.6.2/rouille/macro.router.html Illustrates specifying the type for path parameters within curly braces, enabling type-safe parsing. ```rust (GET) (/{id: u32}/foo) => { ... }, ``` -------------------------------- ### Macro accept! Source: https://docs.rs/rouille/3.6.2/rouille/macro.accept.html The accept! macro allows developers to handle content negotiation by mapping MIME types to specific response values based on the request's Accept header. ```APIDOC ## accept! Macro ### Description Dispatches between blocks depending on the value of the `Accept` header. The macro returns the value corresponding to the MIME type with the highest priority in the request's `Accept` header. ### Syntax `accept!(request, mime1 => value1, mime2 => value2, ...)` ### Parameters - **request** (Request) - The request object to inspect. - **mime => value** (Pair) - A mapping where `mime` is a string representing the MIME type and `value` is the expression to return if that MIME type is selected. ### Behavior - If multiple MIME types have the same priority, the earliest in the list is chosen. - If no MIME matches, the first in the list is chosen. - If no `Accept` header exists, it defaults to `*/*`. ### Example ```rust use rouille::Request; use rouille::Response; fn handle(request: &Request) -> Response { accept!(request, "text/html" => Response::html("

Hello world

"), "text/plain" => Response::text("Hello world"), ) } ``` ``` -------------------------------- ### PartialEq Implementation for HttpAuthCredentials Source: https://docs.rs/rouille/3.6.2/rouille/input/struct.HttpAuthCredentials.html Allows comparison of HttpAuthCredentials instances for equality using `==` and inequality using `!=`. ```rust fn eq(&self, other: &HttpAuthCredentials) -> bool ``` ```rust fn ne(&self, other: &Rhs) -> bool ``` -------------------------------- ### accept Macro Definition Source: https://docs.rs/rouille/3.6.2/rouille/macro.accept.html The signature of the accept macro. ```rust macro_rules! accept { ($request:expr, $($mime:expr => $val:expr),+ $(,)*) => { ... }; } ``` -------------------------------- ### ResponseBody Constructors Source: https://docs.rs/rouille/3.6.2/rouille/struct.ResponseBody.html Methods to instantiate a ResponseBody from different data sources. ```APIDOC ## ResponseBody Constructors ### Description Methods to create a new `ResponseBody` instance from various input types. ### Methods - `empty()`: Creates an empty body. - `from_string(data: S)`: Creates a body from a UTF-8 string. - `from_data(data: D)`: Creates a body from raw bytes (Vec). - `from_file(file: File)`: Creates a body from a file. - `from_reader(data: R)`: Creates a body from a reader (size unknown). - `from_reader_and_size(data: R, size: usize)`: Creates a body from a reader with a known size. ### Request Example ```rust use rouille::ResponseBody; let body = ResponseBody::from_string("hello world"); ``` ``` -------------------------------- ### Router with String-Style URL Source: https://docs.rs/rouille/3.6.2/rouille/macro.router.html Demonstrates an alternative syntax for defining URL routes using strings, which allows for characters not valid in Rust identifiers. ```rust (GET) ["/hello/2"] => { ... }, ``` -------------------------------- ### Create a ResponseBody from a file Source: https://docs.rs/rouille/3.6.2/rouille/struct.ResponseBody.html Creates a response body that streams the content of a file. ```rust use std::fs::File; use rouille::ResponseBody; let file = File::open("page.html").unwrap(); let body = ResponseBody::from_file(file); ``` -------------------------------- ### match_assets Source: https://docs.rs/rouille Utility function to serve static files from a directory based on the request path. ```APIDOC ## match_assets ### Description Searches inside a specified path for a file that matches the request URL. If found, it returns a response containing the file; otherwise, it returns a 404 response. ### Parameters - **request** (Request) - Required - The incoming HTTP request. - **path** (string) - Required - The local directory path to search for static files. ``` -------------------------------- ### Basic HTTP Authentication Source: https://docs.rs/rouille/3.6.2/rouille/input/fn.basic_http_auth.html This snippet demonstrates how to use the `basic_http_auth` function to authenticate users. It attempts to parse the Authorization header. If successful, it checks the provided credentials. If authentication fails, it returns a login-required response. ```APIDOC ## Function basic_http_auth ### Description Attempts to parse a `Authorization` header with basic HTTP auth. If such a header is present and valid, a `HttpAuthCredentials` is returned. ### Method N/A (This is a function, not an HTTP endpoint) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) - **HttpAuthCredentials** (Option) - Contains the login and password if the header is valid. #### Response Example ```rust Some(HttpAuthCredentials { login: "admin".to_string(), password: "GT5GeKyLvKLxuc7mjF5h".to_string() }) ``` ### Error Handling - Returns `None` if the `Authorization` header is missing or invalid. - The example shows how to return a `Response::basic_http_auth_login_required("realm")` if authentication fails. ``` -------------------------------- ### Create an Empty 404 Response Source: https://docs.rs/rouille/3.6.2/rouille/struct.Response.html Use `Response::empty_404` to create an empty response with a 404 Not Found status code. ```rust use rouille::Response; let response = Response::empty_404(); ```