### Basic TCP Listener Setup Source: https://docs.rs/salvo/latest/salvo/conn/index.html?search= Demonstrates how to create and bind a TCP listener for incoming connections. This is a common starting point for setting up a server. ```rust use salvo_core::conn::TcpListener; use salvo_core::prelude::*; #[tokio::main] async fn main() { let acceptor = TcpListener::new("127.0.0.1:7878").bind().await; // Use acceptor with Server } ``` -------------------------------- ### Response Examples Syntax Source: https://docs.rs/salvo/latest/salvo/prelude/endpoint/index.html Details the syntax for defining multiple examples for a single response. ```APIDOC ### §Response `examples(...)` syntax * `name = ...` This is first attribute and value must be literal string. * `summary = ...` Short description of example. Value must be literal string. * `description = ...` Long description of example. Attribute supports markdown for rich text representation. Value must be literal string. * `value = ...` Example value. It must be _`json!(...)`_._`json!(...)`_should be something that _`serde_json::json!`_can parse as a _`serde_json::Value`_. * `external_value = ...` Define URI to literal example value. This is mutually exclusive to the _`value`_attribute. Value must be literal string. _**Example of example definition.**_ ``` ("John" = (summary = "This is John", value = json!({"name": "John"}))) ``` ``` -------------------------------- ### Define Response Example with Name and Summary Source: https://docs.rs/salvo/latest/salvo/prelude/endpoint/index.html Demonstrates how to define a named response example with a summary and a JSON value. This is useful for providing specific examples of expected responses. ```rust ("John" = (summary = "This is John", value = json!({"name": "John"}))) ``` -------------------------------- ### Endpoint with Multiple Examples for a Single Response Source: https://docs.rs/salvo/latest/salvo/prelude/endpoint/index.html Shows how to provide multiple distinct examples for a single response type, each with its own summary and description. ```rust #[salvo_oapi::endpoint( responses=( (status_code = 200, body = User, examples=( ("Demo" = (summary = "This is summary", description = "Long description", value = json!(User{name: "Demo".to_string()}))), ("John" = (summary = "Another user", value = json!({"name": "John"}))) ) ) ) )] async fn get_user() -> Json { Json(User {name: "John".to_string()}) } ``` -------------------------------- ### Uri Parsing Examples Source: https://docs.rs/salvo/latest/salvo/http/uri/struct.Uri.html Examples demonstrating how to parse strings into Uri objects, including handling of query strings. ```APIDOC ## Uri Parsing ### Description Demonstrates parsing a URI string with a query component. ### Code Example ```rust let uri: Uri = "http://example.com?key=value&foo=bar".parse().unwrap(); assert_eq!(uri.query(), Some("key=value&foo=bar")); ``` ### Description Demonstrates parsing a URI string without a query component. ### Code Example ```rust let uri: Uri = "/hello/world".parse().unwrap(); assert!(uri.query().is_none()); ``` ``` -------------------------------- ### Basic Request ID Middleware Setup Source: https://docs.rs/salvo/latest/salvo/request_id/index.html This example demonstrates how to integrate the RequestId middleware into a Salvo application. It shows how to add the middleware to the router and access the generated request ID within a handler. ```rust use salvo_core::prelude::*; use salvo_extra::request_id::RequestId; #[handler] async fn hello(req: &mut Request) -> String { format!("Request id: {:?}", req.header::("x-request-id")) } #[tokio::main] async fn main() { let acceptor = TcpListener::new("0.0.0.0:8698").bind().await; let router = Router::new().hoop(RequestId::new()).get(hello); Server::new(acceptor).serve(router).await; } ``` -------------------------------- ### GET User Endpoint (Multiple Examples) Source: https://docs.rs/salvo/latest/salvo/prelude/endpoint/index.html Defines a GET endpoint for retrieving user information, showcasing multiple examples for a single response type. ```APIDOC ## GET /user ### Description Retrieves user information with multiple example responses provided for demonstration. ### Method GET ### Endpoint /user ### Response #### Success Response (200) - **User** (object) - The user object. #### Response Example ```json { "example": "{\"name\": \"John\"}" } ``` ``` -------------------------------- ### Example TE Header Values Source: https://docs.rs/salvo/latest/salvo/http/headers/struct.Te.html Illustrative examples of valid values for the `TE` header. ```text trailers trailers, deflate;q=0.5 ``` -------------------------------- ### Example Usage Source: https://docs.rs/salvo/latest/salvo/hyper/ext/struct.Protocol.html Demonstrates how to insert a Protocol extension into an HTTP request's extensions. ```APIDOC ## §Example ``` use hyper::ext::Protocol; use http::{Request, Method, Version}; let mut req = Request::new(()); *req.method_mut() = Method::CONNECT; *req.version_mut() = Version::HTTP_2; req.extensions_mut().insert(Protocol::from_static("websocket")); // Now the request will include the `:protocol` pseudo-header with value "websocket" ``` ``` -------------------------------- ### Force HTTPS Redirect Example Source: https://docs.rs/salvo/latest/salvo/force_https/index.html Demonstrates how to apply the ForceHttps middleware to a Salvo service to redirect all requests to HTTPS. This example configures TLS using Rustls and sets up listeners for both HTTPS and HTTP ports. ```rust use salvo_core::prelude::*; use salvo_core::conn::rustls::{Keycert, RustlsConfig}; use salvo_extra::force_https::ForceHttps; #[handler] async fn hello() -> &'static str { "hello" } #[tokio::main] async fn main() { let router = Router::new().get(hello); let service = Service::new(router).hoop(ForceHttps::new().https_port(5443)); let config = RustlsConfig::new( Keycert::new() .cert(include_bytes!("../../core/certs/cert.pem").as_ref()) .key(include_bytes!("../../core/certs/key.pem").as_ref()), ); let acceptor = TcpListener::new("0.0.0.0:5443") .rustls(config) .join(TcpListener::new("0.0.0.0:8698")) .bind() .await; Server::new(acceptor).serve(service).await; } ``` -------------------------------- ### Create a GET Request Source: https://docs.rs/salvo/latest/salvo/hyper/http/request/struct.Request.html Use `Request::get()` to quickly create a `Request` builder pre-configured with the GET method and a specified URI. The body can then be added. ```rust let request = Request::get("https://www.rust-lang.org/") .body(()) .unwrap(); ``` -------------------------------- ### TokioExecutor Example Source: https://docs.rs/salvo/latest/salvo/hyper/rt/trait.Executor.html An example implementation of the Executor trait using Tokio's `spawn` function. ```APIDOC ## §Example ```rust #[derive(Clone)] struct TokioExecutor; impl Executor for TokioExecutor where F: Future + Send + 'static, F::Output: Send + 'static, { fn execute(&self, future: F) { tokio::spawn(future); } } ``` ``` -------------------------------- ### Serve a Service with Server Source: https://docs.rs/salvo/latest/salvo/server/struct.Server.html This example demonstrates how to bind a server to a port and then serve a router. Ensure that the `hello` handler and `main` function are properly defined within your application. ```rust use salvo_core::prelude::* #[handler] async fn hello() -> &'static str { "Hello World" } #[tokio::main] async fn main() { let acceptor = TcpListener::new("0.0.0.0:8698").bind().await; let router = Router::new().get(hello); Server::new(acceptor).serve(router).await; } ``` -------------------------------- ### GET User Endpoint (Multiple Content Types) Source: https://docs.rs/salvo/latest/salvo/prelude/endpoint/index.html Defines a GET endpoint for retrieving user information, supporting multiple content types with specific examples for each. ```APIDOC ## GET /user ### Description Retrieves user information, supporting different API versions via content negotiation. ### Method GET ### Endpoint /user ### Response #### Success Response (200) - **application/vnd.user.v1+json** (object) - User data for version 1. - **application/vnd.user.v2+json** (object) - User data for version 2. #### Response Example ```json { "example": "{\"id\": \"id\"}" } ``` ``` -------------------------------- ### HTTP/1 Builder Configuration Example Source: https://docs.rs/salvo/latest/salvo/conn/http1/struct.Builder.html Demonstrates how to create and configure an HTTP/1 connection builder. Options can be set individually or chained together. ```rust let mut http = Builder::new(); // Set options one at a time http.half_close(false); // Or, chain multiple options http.keep_alive(false).title_case_headers(true).max_buf_size(8192); ``` -------------------------------- ### Get Uri Query Source: https://docs.rs/salvo/latest/salvo/http/uri/struct.Uri.html Retrieves the query string component of a URI, starting after the '?'. ```rust let uri: Uri = "http://example.org/hello/world?key=value".parse().unwrap(); assert_eq!(uri.query(), Some("key=value")); ``` ```rust let uri: Uri = "/hello/world?key=value&foo=bar".parse().unwrap(); assert_eq!(uri.query(), Some("key=value&foo=bar")); ``` -------------------------------- ### WebSocket Server Implementation Source: https://docs.rs/salvo/latest/salvo/websocket/index.html This example demonstrates how to set up a WebSocket server using Salvo. It includes a handler for WebSocket connections that echoes messages back to the client and a basic HTML page to test the connection. Ensure the `websocket` feature is enabled. ```rust use salvo_core::prelude::*; use salvo_extra::websocket::WebSocketUpgrade; use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, Deserialize, Serialize)] struct User { id: usize, name: String, } #[handler] async fn connect(req: &mut Request, res: &mut Response) -> Result<(), StatusError> { let user = req.parse_queries::(); WebSocketUpgrade::new() .upgrade(req, res, |mut ws| async move { println!("{user:#?}" ); while let Some(msg) = ws.recv().await { let msg = if let Ok(msg) = msg { msg } else { // client disconnected return; }; if ws.send(msg).await.is_err() { // client disconnected return; } } }) .await } #[handler] async fn index(res: &mut Response) { res.render(Text::Html(INDEX_HTML)); } #[tokio::main] async fn main() { let router = Router::new().get(index).push(Router::with_path("ws").goal(connect)); let acceptor = TcpListener::new("0.0.0.0:8698").bind().await; Server::new(acceptor).serve(router).await; } static INDEX_HTML: &str = r###" WS

WS

Connecting...

"###; ``` -------------------------------- ### AccessControlAllowOrigin Usage Examples Source: https://docs.rs/salvo/latest/salvo/http/headers/struct.AccessControlAllowOrigin.html Demonstrates how to create instances of AccessControlAllowOrigin for any origin, null origin, and a specific origin. ```rust use headers::AccessControlAllowOrigin; use std::convert::TryFrom; let any_origin = AccessControlAllowOrigin::ANY; let null_origin = AccessControlAllowOrigin::NULL; let origin = AccessControlAllowOrigin::try_from("http://web-platform.test:8000"); ``` -------------------------------- ### Example Cookie values Source: https://docs.rs/salvo/latest/salvo/http/headers/struct.Cookie.html Illustrates common formats for Cookie header values. ```text SID=31d4d96e407aad42 SID=31d4d96e407aad42; lang=en-US ``` -------------------------------- ### Derive ToParameters Implementation Source: https://docs.rs/salvo/latest/salvo/prelude/trait.ToParameters.html Demonstrates how to derive the ToParameters trait for a struct. This is the recommended approach for defining path or query parameters. Note that this example requires additional setup with endpoints to compile. ```rust use salvo_core::prelude::* use salvo_oapi::{Components, EndpointArgRegister, Operation, ToParameters}; use serde::Deserialize; #[derive(Deserialize, ToParameters)] struct PetParams { /// Id of pet id: i64, /// Name of pet name: String, } ``` -------------------------------- ### Server::new Source: https://docs.rs/salvo/latest/salvo/server/struct.Server.html Creates a new Server instance with a given Acceptor. This is the fundamental way to initialize a server to listen for incoming connections. ```APIDOC ## Server::new ### Description Create new `Server` with `Acceptor`. ### Method `Server::new(acceptor: A) -> Server` ### Parameters * **acceptor** (A) - The acceptor to use for listening for connections. ### Example ```rust use salvo_core::prelude::* #[tokio::main] async fn main() { let acceptor = TcpListener::new("127.0.0.1:8698").bind().await; Server::new(acceptor); } ``` ``` -------------------------------- ### Authorization Header Examples Source: https://docs.rs/salvo/latest/salvo/http/headers/struct.Authorization.html Demonstrates how to create `Authorization` headers for Basic and Bearer authentication schemes using provided helper functions. ```rust use headers::Authorization; let basic = Authorization::basic("Aladdin", "open sesame"); let bearer = Authorization::bearer("some-opaque-token").unwrap(); ``` -------------------------------- ### Simple 404 Handler Source: https://docs.rs/salvo/latest/salvo/hyper/http/struct.Response.html An example of creating a basic 404 Not Found response. ```APIDOC ## A simple 404 handler ```rust use http::{Request, Response, StatusCode}; fn not_found(_req: Request<()>) -> http::Result> { Response::builder() .status(StatusCode::NOT_FOUND) .body(()) } ``` ``` -------------------------------- ### Serve a Service with Server Source: https://docs.rs/salvo/latest/salvo/struct.Server.html The `serve` method takes a Service and starts the server to handle incoming requests. Ensure a router or service is correctly defined before calling this. ```rust use salvo_core::prelude::*; #[handler] async fn hello() -> &'static str { "Hello World" } #[tokio::main] async fn main() { let acceptor = TcpListener::new("0.0.0.0:8698").bind().await; let router = Router::new().get(hello); Server::new(acceptor).serve(router).await; } ``` -------------------------------- ### query() Source: https://docs.rs/salvo/latest/salvo/hyper/http/struct.Uri.html Get the query string of this `Uri`, starting after the `?`. The query component contains non-hierarchical data that, along with data in the path component, serves to identify a resource within the scope of the URI’s scheme and naming authority (if any). ```APIDOC ## query() ### Description Get the query string of this `Uri`, starting after the `?`. ### Method `&self.query()` ### Parameters None ### Response - `Option<&str>`: The query string as a `&str`, or None if no query component exists. ### 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")); ``` ``` -------------------------------- ### StaticDir Configuration and Usage Source: https://docs.rs/salvo/latest/salvo/prelude/struct.StaticDir.html Demonstrates how to create and configure a StaticDir handler for serving static files, including setting roots, default files, and enabling directory listing. ```APIDOC ## StaticDir Handler that serves static files from directories. ### Description This handler can serve files from one or more directory paths, with support for directory listing, compressed file variants, and default files. ### Usage Example ```rust use salvo_core::prelude::* use salvo_serve_static::StaticDir; let router = Router::new().push( Router::with_path("static/<**>").get( StaticDir::new(["assets", "static"]) .defaults("index.html") .auto_list(true), ), ); ``` ### Fields - **`roots`** (Vec) - Required - Static root directories to search for files. - **`chunk_size`** (Option) - Optional - Chunk size for file reading (in bytes). - **`include_dot_files`** (bool) - Optional - Whether to include dot files (files/directories starting with .). - **`auto_list`** (bool) - Optional - Whether to automatically list directories when default file isn’t found. - **`compressed_variations`** (HashMap>) - Optional - Map of compression algorithms to file extensions for compressed variants. - **`defaults`** (Vec) - Optional - Default file names to look for in directories (e.g., “index.html”). - **`fallback`** (Option) - Optional - Fallback file to serve when requested file isn’t found. ``` -------------------------------- ### query Source: https://docs.rs/salvo/latest/salvo/http/uri/struct.Uri.html Get the query string of this `Uri`, starting after the `?`. The query component contains non-hierarchical data that, along with data in the path component, serves to identify a resource within the scope of the URI’s scheme and naming authority (if any). The query component is indicated by the first question mark (“?”) character and terminated by a number sign (“#”) character or by the end of the URI. ```APIDOC ## pub fn query(&self) -> Option<&str> ### Description Get the query string of this `Uri`, starting after the `?`. ### 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")); ``` ``` -------------------------------- ### Create a new Server with Acceptor Source: https://docs.rs/salvo/latest/salvo/struct.Server.html Use `Server::new` to create a new server instance with a given Acceptor. This is the fundamental step to start a Salvo server. ```rust use salvo_core::prelude::*; #[tokio::main] async fn main() { let acceptor = TcpListener::new("127.0.0.1:8698").bind().await; Server::new(acceptor); } ``` -------------------------------- ### IfUnmodifiedSince Example Value Source: https://docs.rs/salvo/latest/salvo/http/headers/struct.IfUnmodifiedSince.html An example of a valid IfUnmodifiedSince header value. ```text Sat, 29 Oct 1994 19:43:31 GMT ``` -------------------------------- ### Keycert::new Source: https://docs.rs/salvo/latest/salvo/conn/openssl/struct.Keycert.html Creates a new, empty Keycert instance. ```APIDOC ## Keycert::new ### Description Creates a new Keycert instance. ### Method `pub fn new() -> Keycert` ``` -------------------------------- ### Get Request Method Source: https://docs.rs/salvo/latest/salvo/http/request/struct.Request.html Retrieves the HTTP method of the request. The default method is GET. ```rust let req = Request::default(); assert_eq!(*req.method(), Method::GET); ``` -------------------------------- ### Basic Salvo Web Service with Logger Middleware Source: https://docs.rs/salvo/latest/salvo/logging/index.html Demonstrates setting up a basic Salvo web service with a 'hello world' handler and integrating the Logger middleware. Ensure the 'logging' feature is enabled for your Salvo dependency. ```rust use salvo_core::prelude::*; use salvo_extra::logging::Logger; #[handler] async fn hello() -> &'static str { "Hello World" } #[tokio::main] async fn main() { let router = Router::new().get(hello); let service = Service::new(router).hoop(Logger::new()); let acceptor = TcpListener::new("0.0.0.0:8698").bind().await; Server::new(acceptor).serve(service).await; } ``` -------------------------------- ### Create Server with Acceptor Source: https://docs.rs/salvo/latest/salvo/server/struct.Server.html Use this function to create a new Server instance with a given Acceptor. This is the fundamental way to initialize a server to listen for incoming connections. ```rust use salvo_core::prelude::* #[tokio::main] async fn main() { let acceptor = TcpListener::new("127.0.0.1:8698").bind().await; Server::new(acceptor); } ``` -------------------------------- ### GET Pet by ID Endpoint Source: https://docs.rs/salvo/latest/salvo/prelude/endpoint/index.html Defines a GET endpoint to retrieve a pet by its ID, with path parameters and a simple JSON response. ```APIDOC ## GET /pet/{id} ### Description Retrieves a pet from the database using its unique identifier. ### Method GET ### Endpoint /pet/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the pet. ### Response #### Success Response (200) - **pet** (string) - The pet information. #### Response Example ```json { "example": "{\"pet\": \"1\"}" } ``` ``` -------------------------------- ### Server::serve Source: https://docs.rs/salvo/latest/salvo/server/struct.Server.html Starts the server and begins serving the provided Service. This is an asynchronous operation that will run until the server is stopped. ```APIDOC ## Server::serve ### Description Serve a `Service`. ### Method `async fn serve(self, service: S)` ### Parameters * **service** (S) - The service to serve. Must implement `Into` and be `Send`. ### Example ```rust use salvo_core::prelude::* #[handler] async fn hello() -> &'static str { "Hello World" } #[tokio::main] async fn main() { let acceptor = TcpListener::new("0.0.0.0:8698").bind().await; let router = Router::new().get(hello); Server::new(acceptor).serve(router).await; } ``` ``` -------------------------------- ### SseEvent Construction and Configuration Source: https://docs.rs/salvo/latest/salvo/sse/struct.SseEvent.html Demonstrates how to create and configure an SseEvent using its builder-like methods. ```APIDOC ## SseEvent Methods ### `text(self, data: T) -> SseEvent` Sets Server-sent event data. ### `json(self, data: T) -> Result` Sets Server-sent event data. Requires the data to implement `Serialize`. ### `comment(self, comment: T) -> SseEvent` Sets Server-sent event comment. ### `name(self, event: T) -> SseEvent` Sets Server-sent event name. ### `retry(self, duration: Duration) -> SseEvent` Sets Server-sent event retry duration. ### `id(self, id: T) -> SseEvent` Sets Server-sent event ID. ``` -------------------------------- ### Get reference to trailers frame content Source: https://docs.rs/salvo/latest/salvo/http/body/struct.BytesFrame.html Use `trailers_ref` to get an optional reference to the HeaderMap if the BytesFrame is a trailers frame. Returns None otherwise. ```rust pub fn trailers_ref(&self) -> Option<&HeaderMap> ``` -------------------------------- ### Get reference to DATA frame content Source: https://docs.rs/salvo/latest/salvo/http/body/struct.BytesFrame.html Use `data_ref` to get an optional reference to the Bytes if the BytesFrame is a DATA frame. Returns None otherwise. ```rust pub fn data_ref(&self) -> Option<&T> ``` -------------------------------- ### FlexFactory::new Source: https://docs.rs/salvo/latest/salvo/fuse/flex/struct.FlexFactory.html Creates a new FlexFactory instance with default configurations. ```APIDOC ## FlexFactory::new ### Description Create a new `FlexFactory`. ### Method `FlexFactory::new()` ### Returns - `FlexFactory`: A new instance of `FlexFactory`. ``` -------------------------------- ### Server::serve Source: https://docs.rs/salvo/latest/salvo/struct.Server.html Starts the server and begins serving a given Service. The server will listen for incoming connections and process them according to the provided Service. This is an asynchronous operation. ```APIDOC ## Server::serve ### Description Serve a `Service`. ### Method `async fn serve(self, service: S)` where `S: Into + Send` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use salvo_core::prelude::* #[handler] async fn hello() -> &'static str { "Hello World" } #[tokio::main] async fn main() { let acceptor = TcpListener::new("0.0.0.0:8698").bind().await; let router = Router::new().get(hello); Server::new(acceptor).serve(router).await; } ``` ### Response #### Success Response The server starts serving the provided service. #### Response Example None ``` -------------------------------- ### Get mutable reference to trailers frame content Source: https://docs.rs/salvo/latest/salvo/http/body/struct.BytesFrame.html Use `trailers_mut` to get an optional mutable reference to the HeaderMap if the BytesFrame is a trailers frame. Returns None otherwise. ```rust pub fn trailers_mut(&mut self) -> Option<&mut HeaderMap> ``` -------------------------------- ### Minimal Endpoint with Request Body and Parameters Source: https://docs.rs/salvo/latest/salvo/prelude/endpoint/index.html A minimal example demonstrating endpoint definition with a request body, responses, and header parameters. ```rust #[salvo_oapi::endpoint( request_body = Pet, responses=( (status_code = 200, description = "Pet stored successfully", body = Pet, headers=( ("x-cache-len", description = "Cache length") ) ), ), parameters( ("x-csrf-token", Header, description = "Current csrf token of user"), ) )] fn post_pet(res: &mut Response) { res.render(Json(Pet { id: 4, name: "bob the cat".to_string(), })); } ``` -------------------------------- ### Get mutable reference to DATA frame content Source: https://docs.rs/salvo/latest/salvo/http/body/struct.BytesFrame.html Use `data_mut` to get an optional mutable reference to the Bytes if the BytesFrame is a DATA frame. Returns None otherwise. ```rust pub fn data_mut(&mut self) -> Option<&mut T> ``` -------------------------------- ### Try Get Query Parameter Source: https://docs.rs/salvo/latest/salvo/struct.Request.html Tries to get a query parameter value, deserializing it to the specified type. Returns a Result with either the deserialized value or a ParseError if parsing fails. ```rust let page: Result = req.try_query("page"); ``` -------------------------------- ### init Source: https://docs.rs/salvo/latest/salvo/conn/quinn/struct.QuinnConnection.html Initializes a with the given initializer. ```APIDOC ## unsafe fn init(init: ::Init) -> usize ### Description Initializes a with the given initializer. ### Method `init` ### Parameters - **init** (::Init) - The initializer value. ### Response - **usize** - The pointer to the initialized memory. ``` -------------------------------- ### Basic Salvo Application Test Source: https://docs.rs/salvo/latest/salvo/test/index.html Demonstrates how to set up a simple Salvo application and test its 'hello' endpoint using TestClient. This example requires the 'test' feature flag. ```rust use salvo_core::prelude::*; #[handler] async fn hello() -> &'static str { "Hello" } fn route() -> Router { Router::new().goal(hello) } #[tokio::main] async fn main() { let acceptor = TcpListener::new("0.0.0.0:8698").bind().await; Server::new(acceptor).serve(route()).await; } #[cfg(test)] mod tests { use salvo_core::prelude::*; use salvo_core::test::{ResponseExt, TestClient}; #[tokio::test] async fn test_hello() { let service = Service::new(super::route()); let content = TestClient::get("http://0.0.0.0:8698/") .send(&service) .await .take_string() .await .unwrap(); assert!(content.contains("Hello")); } } ``` -------------------------------- ### Try Get Query or Form Parameter Source: https://docs.rs/salvo/latest/salvo/struct.Request.html Tries to get a value from query parameters first, falling back to form data. Returns a Result with either the deserialized value or a ParseError. ```rust let value: Result = req.try_query_or_form("my_param").await; ``` -------------------------------- ### Builder Configuration Source: https://docs.rs/salvo/latest/salvo/conn/http1/struct.Builder.html Demonstrates how to create and configure a Builder instance for HTTP/1 server connections. ```APIDOC ## Builder Configuration ### Description This section details the methods available on the `Builder` struct for configuring HTTP/1 server connections. Users can create a new builder and then chain method calls to set various options. ### Methods #### `new()` Creates a new `Builder` instance with default settings. #### `half_close(val: bool)` Configures whether HTTP/1 connections should support half-closures. Defaults to `false`. #### `keep_alive(val: bool)` Enables or disables HTTP/1 keep-alive. Defaults to `true`. #### `title_case_headers(enabled: bool)` Determines if header names are written in title case. Defaults to `false`. #### `allow_multiple_spaces_in_request_line_delimiters(enabled: bool)` Allows or disallows multiple spaces as delimiters in request lines. Defaults to `false`. #### `ignore_invalid_headers(enabled: bool)` Silently ignores malformed header lines if enabled. Defaults to `false`. #### `preserve_header_case(enabled: bool)` Supports preserving the original case of header names. Defaults to `false`. #### `max_headers(val: usize)` Sets the maximum number of headers allowed in a request. Defaults to `100`. Setting this value may impact performance. #### `header_read_timeout(read_timeout: impl Into>)` Sets a timeout for reading client request headers. Requires a `Timer` to be set. Pass `None` to disable. Defaults to 30 seconds. #### `writev(val: bool)` Configures whether to use vectored writes. Defaults to `auto`. #### `max_buf_size(max: usize)` Sets the maximum buffer size for the connection. Minimum value is 8192. Defaults to approximately 400kb. #### `auto_date_header(enabled: bool)` Includes the `date` header in HTTP responses if enabled. Defaults to `true`. #### `pipeline_flush(enabled: bool)` Aggregates flushes to better support pipelined responses. This is an experimental feature. Defaults to `false`. ### Example ```rust let mut http = Builder::new(); http.half_close(false); http.keep_alive(false).title_case_headers(true).max_buf_size(8192); ``` ``` -------------------------------- ### Try Get Form or Query Parameter Source: https://docs.rs/salvo/latest/salvo/struct.Request.html Tries to get a value from form data first, falling back to query parameters. Returns a Result with either the deserialized value or a ParseError. ```rust let value: Result = req.try_form_or_query("my_param").await; ``` -------------------------------- ### QuinnAcceptor::new Source: https://docs.rs/salvo/latest/salvo/conn/quinn/struct.QuinnAcceptor.html Creates a new QuinnAcceptor instance, which is used to accept incoming QUIC connections. ```APIDOC ## pub fn new(endpoint: Endpoint, socket: SocketAddr, cancel_reload: CancellationToken) -> QuinnAcceptor ### Description Create a new `QuinnAcceptor`. ### Parameters - **endpoint** (Endpoint) - The QUIC endpoint configuration. - **socket** (SocketAddr) - The local address to bind the acceptor to. - **cancel_reload** (CancellationToken) - A token to signal cancellation for reloading. ### Returns A new `QuinnAcceptor` instance. ``` -------------------------------- ### type_id Source: https://docs.rs/salvo/latest/salvo/conn/quinn/struct.QuinnConnection.html Gets the `TypeId` of `self`. ```APIDOC ## fn type_id(&self) -> TypeId ### Description Gets the `TypeId` of `self`. ### Method `type_id` ### Parameters None ### Response - **TypeId**: The type identifier of the object. ``` -------------------------------- ### Creating a Uri from Parts (Relative) Source: https://docs.rs/salvo/latest/salvo/hyper/http/struct.Uri.html Demonstrates creating a relative `Uri` from `Parts` by setting only the path and query. ```rust let mut parts = Parts::default(); parts.path_and_query = Some("/foo".parse().unwrap()); let uri = Uri::from_parts(parts).unwrap(); assert_eq!(uri.path(), "/foo"); assert!(uri.scheme().is_none()); assert!(uri.authority().is_none()); ``` -------------------------------- ### Try to Get Query Parameter Source: https://docs.rs/salvo/latest/salvo/prelude/struct.Request.html Tries to get a query parameter value, deserializing it to the specified type. Returns a `ParseResult` with either the deserialized value or an error indicating why parsing failed. Use this for detailed error handling. ```rust let page: u32 = req.try_query("page")?; ``` -------------------------------- ### Salvo Response Links Syntax Example Source: https://docs.rs/salvo/latest/salvo/prelude/endpoint/index.html Demonstrates the syntax for defining response links with operation references, parameters, request bodies, and server information. ```rust responses( (status = 200, description = "success response", links( ("link_name" = ( operation_id = "test_links", parameters(("key" = "value"), ("json_value" = json!(1))), request_body = "this is body", server(url = "http://localhost") )) ) ) ) ``` -------------------------------- ### Implement Basic Authentication in Salvo Source: https://docs.rs/salvo/latest/salvo/basic_auth/index.html?search= This example demonstrates how to set up and use the BasicAuth middleware in a Salvo application. It includes defining a custom validator and integrating the middleware with a router. ```rust use salvo_core::prelude::*; use salvo_extra::basic_auth::{BasicAuth, BasicAuthValidator}; struct Validator; impl BasicAuthValidator for Validator { async fn validate(&self, username: &str, password: &str, _depot: &mut Depot) -> bool { username == "root" && password == "pwd" } } #[handler] async fn hello() -> &'static str { "Hello" } #[tokio::main] async fn main() { let auth_handler = BasicAuth::new(Validator); let router = Router::with_hoop(auth_handler).goal(hello); let acceptor = TcpListener::new("0.0.0.0:8698").bind().await; Server::new(acceptor).serve(router).await; } ``` -------------------------------- ### port_u16 Source: https://docs.rs/salvo/latest/salvo/http/uri/struct.Uri.html Get the port of this `Uri` as a `u16`. ```APIDOC ## pub fn port_u16(&self) -> Option ### Description Get the port of this `Uri` as a `u16`. ### Example ```rust let uri: Uri = "http://example.org:80/hello/world".parse().unwrap(); assert_eq!(uri.port_u16(), Some(80)); ``` ``` -------------------------------- ### Create Uri from Parts (Relative) Source: https://docs.rs/salvo/latest/salvo/http/uri/struct.Uri.html Demonstrates creating a relative `Uri` from `Parts`, setting only the path and query. ```rust use http::uri::Parts; use http::Uri; let mut parts = Parts::default(); parts.path_and_query = Some("/foo".parse().unwrap()); let uri = Uri::from_parts(parts).unwrap(); assert_eq!(uri.path(), "/foo"); assert!(uri.scheme().is_none()); assert!(uri.authority().is_none()); ``` -------------------------------- ### scheme_str Source: https://docs.rs/salvo/latest/salvo/http/uri/struct.Uri.html Get the scheme of this `Uri` as a `&str`. ```APIDOC ## pub fn scheme_str(&self) -> Option<&str> ### Description Get the scheme of this `Uri` as a `&str`. ### Example ```rust let uri: Uri = "http://example.org/hello/world".parse().unwrap(); assert_eq!(uri.scheme_str(), Some("http")); ``` ``` -------------------------------- ### Get Session Source: https://docs.rs/salvo/latest/salvo/struct.Depot.html Retrieves a reference to the session from the depot. ```APIDOC ## fn session(&self) -> Option<&Session> ### Description Get session reference ### Signature `fn session(&self) -> Option<&Session>` ``` -------------------------------- ### Compression::new Source: https://docs.rs/salvo/latest/salvo/prelude/struct.Compression.html Creates a new `Compression` instance with default settings. ```APIDOC ## `new()` ### Description Create a new `Compression`. ### Returns A new `Compression` instance. ``` -------------------------------- ### Init Source: https://docs.rs/salvo/latest/salvo/conn/quinn/struct.QuinnConnection.html The type for initializers. ```APIDOC ## type Init = T ### Description The type for initializers. ### Method `Init` ### Parameters None ### Response - **T** - The type of the initializer. ``` -------------------------------- ### BasicAuth::realm Source: https://docs.rs/salvo/latest/salvo/basic_auth/struct.BasicAuth.html Gets the realm of the Basic Authentication. ```APIDOC ## pub fn realm(&self) -> &str ### Description Get the realm of the Basic Authentication. ### Signature ```rust pub fn realm(&self) -> &str ``` ### Returns A string slice representing the current realm. ``` -------------------------------- ### Try Get Form Field Source: https://docs.rs/salvo/latest/salvo/struct.Request.html Tries to get a form field value, deserializing it to the specified type. Returns a Result with either the deserialized value or a ParseError if parsing fails. This method parses the request body as form data on first call. ```rust let username: Result = req.try_form("username").await; ``` -------------------------------- ### Opening Files Source: https://docs.rs/salvo/latest/salvo/fs/struct.NamedFile.html Demonstrates how to open files using NamedFile, either directly or with a builder for more control over options like attached name and buffer size. ```APIDOC ## Opening Files Files can be opened directly or through a builder: ```rust use salvo_core::fs::NamedFile; async fn examples() { // Simple open let file = NamedFile::open("document.pdf").await; // Builder pattern for more control let file = NamedFile::builder("document.pdf") .attached_name("report.pdf") .buffer_size(65536) .build() .await; } ``` ``` -------------------------------- ### Try Get Query Parameter with Error Handling Source: https://docs.rs/salvo/latest/salvo/http/struct.Request.html Tries to get a query parameter value by key and deserialize it. Returns a `Result` containing either the deserialized value or a `ParseError` indicating why parsing failed. Use this when detailed error information is required. ```rust let value: Result = req.try_query("key"); ``` -------------------------------- ### Create a Connection header Source: https://docs.rs/salvo/latest/salvo/http/headers/struct.Connection.html Demonstrates how to create a `Connection` header with the `keep-alive` option. ```rust use headers::Connection; let keep_alive = Connection::keep_alive(); ``` -------------------------------- ### Try to Get Form Field Source: https://docs.rs/salvo/latest/salvo/prelude/struct.Request.html Tries to get a form field value, deserializing it to the specified type. Returns a `ParseResult` with either the deserialized value or an error indicating why parsing failed. This method parses the request body as form data on first call. ```rust let username: String = req.try_form("username").await?; ``` -------------------------------- ### Example Usage of Depot in Salvo Handlers Source: https://docs.rs/salvo/latest/salvo/struct.Depot.html Demonstrates how to insert and retrieve data from a Depot within Salvo's request handling pipeline. Use this to share request-specific data across middlewares and handlers. ```rust use salvo_core::prelude::*; #[handler] async fn set_user(depot: &mut Depot) { depot.insert("user", "client"); } #[handler] async fn hello(depot: &mut Depot) -> String { format!( "Hello {{}}", depot.get::<&str>("user").copied().unwrap_or_default() ) } #[tokio::main] async fn main() { let router = Router::new().hoop(set_user).goal(hello); let acceptor = TcpListener::new("0.0.0.0:8698").bind().await; Server::new(acceptor).serve(router).await; } ``` -------------------------------- ### Depot::inner() Source: https://docs.rs/salvo/latest/salvo/struct.Depot.html Get reference to depot inner map. ```APIDOC ## Depot::inner() ### Description Get reference to depot inner map. ### Signature ```rust pub fn inner(&self) -> &HashMap> ``` ``` -------------------------------- ### Creating a Response Source: https://docs.rs/salvo/latest/salvo/hyper/http/struct.Response.html Demonstrates how to construct an HTTP response using `Response::builder()`, setting headers and status codes. ```APIDOC ## Creating a `Response` to return ```rust use http::{Request, Response, StatusCode}; fn respond_to(req: Request<()>) -> http::Result> { let mut builder = Response::builder() .header("Foo", "Bar") .status(StatusCode::OK); if req.headers().contains_key("Another-Header") { builder = builder.header("Another-Header", "Ack"); } builder.body(()) } ``` ``` -------------------------------- ### Create a New Keycert Source: https://docs.rs/salvo/latest/salvo/conn/openssl/struct.Keycert.html Initializes a new, empty Keycert instance. This is the starting point for configuring TLS keys and certificates. ```rust pub fn new() -> Keycert ``` -------------------------------- ### Get HeaderValue Length Source: https://docs.rs/salvo/latest/salvo/http/header/struct.HeaderValue.html Returns the length of the HeaderValue in bytes. ```rust let val = HeaderValue::from_static("hello"); assert_eq!(val.len(), 5); ``` -------------------------------- ### NamedFile::last_modified Source: https://docs.rs/salvo/latest/salvo/fs/struct.NamedFile.html Gets the `Last-Modified` timestamp for the file, if generated. ```APIDOC #### pub fn last_modified(&self) -> Option GEt last_modified value. ``` -------------------------------- ### NamedFile::etag Source: https://docs.rs/salvo/latest/salvo/fs/struct.NamedFile.html Gets the ETag value for the file, if generated. ```APIDOC #### pub fn etag(&self) -> Option Get ETag value. ``` -------------------------------- ### Create a new Router Source: https://docs.rs/salvo/latest/salvo/struct.Router.html Initializes a new `Router` instance. No specific setup or imports are required beyond the `Router` definition itself. ```rust pub fn new() -> Router ``` -------------------------------- ### NamedFile::content_disposition Source: https://docs.rs/salvo/latest/salvo/fs/struct.NamedFile.html Gets the `Content-Disposition` header value, if set. ```APIDOC #### pub fn content_disposition(&self) -> Option<&HeaderValue> Get Content-Disposition value. ``` -------------------------------- ### OpensslListener::new Source: https://docs.rs/salvo/latest/salvo/conn/openssl/struct.OpensslListener.html Creates a new OpensslListener with a configuration stream and an inner listener. ```APIDOC ## pub fn new(config_stream: S, inner: T) -> OpensslListener ### Description Create new OpensslListener with config stream. ### Parameters - **config_stream**: S - The configuration stream. - **inner**: T - The inner listener. ``` -------------------------------- ### Create New Compression Instance Source: https://docs.rs/salvo/latest/salvo/prelude/struct.Compression.html Initializes a new `Compression` struct with default settings. ```rust pub fn new() -> Compression ``` -------------------------------- ### NamedFile::content_type Source: https://docs.rs/salvo/latest/salvo/fs/struct.NamedFile.html Gets the MIME `Content-Type` value for the file. ```APIDOC #### pub fn content_type(&self) -> &Mime Get content type value. ``` -------------------------------- ### QuinnListener::new Source: https://docs.rs/salvo/latest/salvo/conn/struct.QuinnListener.html Constructs a new QuinnListener, binding to a socket address. ```APIDOC ## new(config_stream: S, local_addr: T) -> QuinnListener ### Description Bind to socket address. ### Parameters #### Path Parameters - **config_stream** (S) - Description not available - **local_addr** (T) - Description not available ### Returns - **QuinnListener** - A new QuinnListener instance. ``` -------------------------------- ### impl Any for T Source: https://docs.rs/salvo/latest/salvo/extract/metadata/enum.SourceFrom.html Provides the `type_id` method to get the `TypeId` of an object. ```APIDOC ## fn type_id(&self) -> TypeId ### Description Gets the `TypeId` of `self`. ### Method `type_id` ``` -------------------------------- ### Try Get Form Field with Error Handling Source: https://docs.rs/salvo/latest/salvo/http/struct.Request.html Tries to get a form field value by key and deserialize it. Returns a `Result` containing either the deserialized value or a `ParseError` indicating why parsing failed. This method parses the request body as form data on the first call. ```rust let value: Result = req.try_form("key").await; ``` -------------------------------- ### Configure StaticDir with default files Source: https://docs.rs/salvo/latest/salvo/prelude/struct.StaticDir.html Set a list of default filenames (e.g., 'index.html') to be served when a directory is requested. The first matching file in the list will be used. ```rust pub fn defaults(self, defaults: impl IntoVecString) -> StaticDir ``` -------------------------------- ### RustlsConfig::new Source: https://docs.rs/salvo/latest/salvo/conn/rustls/struct.RustlsConfig.html Creates a new RustlsConfig with an optional fallback Keycert. ```APIDOC ## RustlsConfig::new ### Description Creates new `RustlsConfig`. ### Signature ```rust pub fn new(fallback: impl Into>) -> RustlsConfig ``` ``` -------------------------------- ### InvalidStreamId Struct Source: https://docs.rs/salvo/latest/salvo/proto/quic/struct.InvalidStreamId.html Represents an invalid StreamId, for example because it’s too large. ```APIDOC ## Struct InvalidStreamId `salvo::proto::quic::InvalidStreamId` ### Description Invalid StreamId, for example because it’s too large. ### Summary ```rust pub struct InvalidStreamId(/* private fields */); ``` ### Trait Implementations #### `impl Debug for InvalidStreamId` ##### `fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>` Formats the value using the given formatter. #### `impl Display for InvalidStreamId` ##### `fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>` Formats the value using the given formatter. #### `impl PartialEq for InvalidStreamId` ##### `fn eq(&self, other: &InvalidStreamId) -> bool` Tests for `self` and `other` values to be equal. ##### `fn ne(&self, other: &Rhs) -> bool` Tests for `!=`. #### `impl StructuralPartialEq for InvalidStreamId` ``` -------------------------------- ### Uri TryFrom Implementation Source: https://docs.rs/salvo/latest/salvo/hyper/http/struct.Uri.html Demonstrates converting `Parts` into a `Uri` object. ```APIDOC ## Uri TryFrom Implementation ### Description This covers the `TryFrom` trait implementation for `Uri`, allowing the construction of a `Uri` object from its constituent `Parts`. ### Method Signature `type Error = InvalidUriParts` `fn try_from(parts: Parts) -> Result` ### Usage Example ```rust // Assuming Parts struct and its creation are defined elsewhere // let parts = Parts { scheme: Some("http".to_string()), host: Some("example.com".to_string()), ..Default::default() }; // let uri: Uri = Uri::try_from(parts).expect("Failed to create Uri from Parts"); ``` ``` -------------------------------- ### Get Mutable Session Source: https://docs.rs/salvo/latest/salvo/struct.Depot.html Retrieves a mutable reference to the session from the depot. ```APIDOC ## fn session_mut(&mut self) -> Option<&mut Session> ### Description Get session mutable reference ### Signature `fn session_mut(&mut self) -> Option<&mut Session>` ``` -------------------------------- ### Build Quinn Server Config Source: https://docs.rs/salvo/latest/salvo/conn/rustls/struct.RustlsConfig.html Builds a server configuration compatible with the Quinn library. This is only available when the 'quinn' crate feature is enabled. ```rust pub fn build_quinn_config(self) -> Result ``` -------------------------------- ### NamedFile::content_encoding Source: https://docs.rs/salvo/latest/salvo/fs/struct.NamedFile.html Gets the content encoding value reference, if set. ```APIDOC #### pub fn content_encoding(&self) -> Option<&HeaderValue> Get content encoding value reference. ```