### Rovo Routing Example with #[rovo] Handlers Source: https://docs.rs/rovo/0.2.3/rovo/routing/index_search= This example demonstrates how to use rovo's routing functions with handlers decorated by #[rovo]. It showcases defining routes for GET, POST, PATCH, and DELETE HTTP methods, with handlers automatically including their documentation. Dependencies include rovo, aide, and axum. ```rust use rovo::{Router, rovo, routing::{get, post, patch, delete}, aide::axum::IntoApiResponse}; use rovo::response::Json; #[rovo] async fn list_items() -> impl IntoApiResponse { Json(()) } #[rovo] async fn create_item() -> impl IntoApiResponse { Json(()) } #[rovo] async fn get_item() -> impl IntoApiResponse { Json(()) } #[rovo] async fn update_item() -> impl IntoApiResponse { Json(()) } #[rovo] async fn delete_item() -> impl IntoApiResponse { Json(()) } Router::new() .route("/items", get(list_items).post(create_item)) .route("/items/{id}", get(get_item).patch(update_item).delete(delete_item)); ``` -------------------------------- ### Rovo Routing Example with axum handlers Source: https://docs.rs/rovo/0.2.3/rovo/routing/index Demonstrates how to use rovo's routing functions (get, post, patch, delete) with handlers decorated by #[rovo]. This example showcases setting up routes for CRUD operations on items. ```rust use rovo::{Router, rovo, routing::{get, post, patch, delete}, aide::axum::IntoApiResponse}; use rovo::response::Json; #[rovo] async fn list_items() -> impl IntoApiResponse { Json(()) } #[rovo] async fn create_item() -> impl IntoApiResponse { Json(()) } #[rovo] async fn get_item() -> impl IntoApiResponse { Json(()) } #[rovo] async fn update_item() -> impl IntoApiResponse { Json(()) } #[rovo] async fn delete_item() -> impl IntoApiResponse { Json(()) } Router::new() .route("/items", get(list_items).post(create_item)) .route("/items/{id}", get(get_item).patch(update_item).delete(delete_item)); ``` -------------------------------- ### Create and configure rovo Router Source: https://docs.rs/rovo/0.2.3/rovo/struct.Router_search= Demonstrates the creation of a `rovo::Router` instance, adding a documented route using `get`, and configuring OpenAPI specifications with a custom title. This is a fundamental example of building a documented API with rovo. ```rust let mut api = OpenApi::default(); api.info.title = "My API".to_string(); let app = Router::new() .route("/documented", get(documented_handler)) .with_oas(api); ``` -------------------------------- ### Redirect Example Usage Source: https://docs.rs/rovo/0.2.3/rovo/response/struct.Redirect_search= Example demonstrating how to use the Redirect struct within an Axum application. ```APIDOC ## §Example ``` use axum::{ routing::get, response::Redirect, Router, }; let app = Router::new() .route("/old", get(|| async {{ Redirect::permanent("/new") }})) .route("/new", get(|| async {{ "Hello!" }})); ``` ``` -------------------------------- ### Rovo Documentation Format: Examples Section Source: https://docs.rs/rovo/0.2.3/rovo/index This code example shows how to provide example responses in Rovo documentation using Rust expressions within doc comments. It includes examples for both a successful response (200) with a `User` struct and a not-found response (404) with an empty tuple. ```rust /// # Examples /// /// 200: User { id: 1, name: "Alice".into() } /// 404: () ``` -------------------------------- ### SSE Handler Example Source: https://docs.rs/rovo/0.2.3/rovo/response/sse/index_search=std%3A%3Avec An example demonstrating how to set up an SSE endpoint using the rovo crate with Axum. This includes creating a stream of events and configuring keep-alive messages. ```APIDOC ## GET /sse ### Description This endpoint provides a Server-Sent Events (SSE) stream that repeatedly sends a 'hi!' message every second. ### Method GET ### Endpoint /sse ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **Content-Type** (string) - `text/event-stream` - **Connection** (string) - `keep-alive` - **Data** (string) - The event data, e.g., `data: hi!` - **Event** (string, optional) - The event name - **Id** (string, optional) - The event ID - **Retry** (integer, optional) - The reconnection time in milliseconds #### Response Example ``` data: hi! ``` ``` data: hi! ``` ``` data: hi! ``` ``` -------------------------------- ### User API Endpoint Example Source: https://docs.rs/rovo/0.2.3/rovo/index_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E This example demonstrates how to document a 'get_user' API endpoint using Rovo's macro and doc comment features. It includes response definitions, metadata tags, and response examples. ```APIDOC ## GET /users/{id} ### Description Get user by ID ### Method GET ### Endpoint /users/{id} ### Parameters #### Path Parameters - **id** (u32) - Required - The ID of the user to retrieve. ### Request Body This endpoint does not accept a request body. ### Response #### Success Response (200) - **Json** - User found successfully #### Error Response (404) - **()** - User not found ### Response Example #### 200 OK ```json { "id": 1, "name": "Alice" } ``` #### 404 Not Found ```json null ``` ### Metadata - **tag**: users ``` -------------------------------- ### Rust: Create GET Request Source: https://docs.rs/rovo/0.2.3/rovo/extract/type.Request_search=std%3A%3Avec Shows how to initiate the creation of a GET request using the Request::get() method. ```rust let request = Request::get("https://www.rust-lang.org/") .body(()) // Assuming Body is Send + Sync .unwrap(); ``` -------------------------------- ### Response Examples Source: https://docs.rs/rovo/0.2.3/rovo/response/type.Response_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Illustrative examples of using the Response struct, including mapping and byte conversion. ```APIDOC ## Examples ```rust let response = Response::builder().body("some string").unwrap(); let mapped_response: Response<&[u8]> = response.map(|b| { assert_eq!(b, "some string"); b.as_bytes() }); assert_eq!(mapped_response.body(), &"some string".as_bytes()); ``` ``` -------------------------------- ### Rust Example: Creating an Axum Router with Redirects Source: https://docs.rs/rovo/0.2.3/rovo/response/struct.Redirect_search=u32+-%3E+bool Demonstrates how to use the `Redirect` struct within an Axum web application to set up routes that issue permanent redirects. This example shows the integration of `Redirect::permanent` with Axum's routing capabilities. ```rust use axum::{ routing::get, response::Redirect, Router, }; let app = Router::new() .route("/old", get(|| async {{ Redirect::permanent("/new") }})) .route("/new", get(|| async {{ "Hello!" }})); ``` -------------------------------- ### Create HTTP Redirects in Rust with Axum Source: https://docs.rs/rovo/0.2.3/rovo/response/struct.Redirect_search= Demonstrates how to create different types of HTTP redirects (permanent, temporary, see other) using the `Redirect` struct from the `rovo` crate within an Axum web application. This example requires the `axum` and `rovo` crates. It showcases creating routes that return permanent redirects and simple GET routes. ```rust use axum::{ routing::get, response::Redirect, Router, }; let app = Router::new() .route("/old", get(|| async { Redirect::permanent("/new") })) .route("/new", get(|| async { "Hello!" })); ``` -------------------------------- ### rovo Documentation Format Example Source: https://docs.rs/rovo/0.2.3/rovo/attr.rovo_search= Illustrates how to structure doc comments for the rovo macro to define OpenAPI documentation. This includes sections for responses, examples, and metadata annotations. ```rust /// Get a single Todo item. /// /// Retrieve a Todo item by its ID from the database. /// /// # Responses /// /// 200: Json - Successfully retrieved the todo item /// 404: () - Todo item was not found /// /// # Examples /// /// 200: TodoItem::default() /// /// # Metadata /// /// @tag todos #[rovo] async fn get_todo( State(app): State, Path(todo): Path ) -> impl IntoApiResponse { // ... } ``` -------------------------------- ### Rovo Documentation Format: Examples Section Source: https://docs.rs/rovo/0.2.3/rovo/index_search= This snippet demonstrates how to provide example responses for different HTTP status codes using Rovo's documentation format. It shows valid Rust expressions for both a successful user object (200) and an empty response for not found (404). These examples are crucial for generating a more comprehensive and user-friendly OpenAPI documentation. ```rust /// # Examples /// /// 200: User { id: 1, name: "Alice".into() } /// 404: () ``` -------------------------------- ### Rust: Create GET Request Source: https://docs.rs/rovo/0.2.3/rovo/extract/type.Request_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Shows how to create an HTTP GET request using the `Request::get()` convenience method in Rust. This method initializes the builder with the GET method and a specified URI. ```rust let request = Request::get("https://www.rust-lang.org/") .body(()) .unwrap(); ``` -------------------------------- ### SSE Handler Example using Axum and Tokio Source: https://docs.rs/rovo/0.2.3/rovo/response/sse/index Demonstrates how to create a Server-Sent Events (SSE) handler using the Axum web framework and Tokio streams. This example sets up a route that sends a repeating 'hi!' event every second. It requires the `axum`, `tokio-stream`, and `futures-util` crates. ```rust use axum::{ Router, routing::get, response::sse::{Event, KeepAlive, Sse}, }; use std::time::Duration; use tokio_stream::StreamExt as _ ; use futures_util::stream::{self, Stream}; let app = Router::new().route("/sse", get(sse_handler)); async fn sse_handler() -> Sse>> { // A `Stream` that repeats an event every second let stream = stream::repeat_with(|| Event::default().data("hi!")) .map(Ok) .throttle(Duration::from_secs(1)); Sse::new(stream).keep_alive(KeepAlive::default()) } ``` -------------------------------- ### MatchedPath with Middleware Example Source: https://docs.rs/rovo/0.2.3/rovo/extract/struct.MatchedPath_search=std%3A%3Avec Shows how to access MatchedPath from request extensions in middleware, for example, with `TraceLayer`. ```APIDOC ## Middleware TraceLayer with MatchedPath ### Description Uses `TraceLayer` middleware to log the matched path of incoming requests by accessing `MatchedPath` from request extensions. ### Method All (GET, POST, PUT, DELETE, etc.) ### Endpoint Any configured route (e.g., /users/{id}) ### Parameters None ### Request Example None ### Response Success Response (200) - The response from the actual route handler. Response Example ```json { "message": "Success" } ``` ### Logs (Example log output from tracing) ``` INFO http-request: "/users/123" ``` ``` -------------------------------- ### Example Usage of rovo Macro (Rust) Source: https://docs.rs/rovo/0.2.3/rovo/attr.rovo_search=u32+-%3E+bool Demonstrates how to use the `#[rovo]` macro with doc comments to define API responses, examples, and metadata for an async Rust function. This includes specifying status codes, response types, example data, tags, and security schemes. ```rust /// Get a single Todo item. /// /// Retrieve a Todo item by its ID from the database. /// /// # Responses /// /// 200: Json - Successfully retrieved the todo item /// 404: () - Todo item was not found /// /// # Examples /// /// 200: TodoItem::default() /// /// # Metadata /// /// @tag todos #[rovo] async fn get_todo( State(app): State, Path(todo): Path ) -> impl IntoApiResponse { // ... } ``` ```rust /// This is a deprecated endpoint. /// /// # Metadata /// /// @tag admin /// @security bearer_auth #[deprecated] #[rovo] async fn old_handler() -> impl IntoApiResponse { // ... } ``` -------------------------------- ### Rust Result unwrap Method Example Source: https://docs.rs/rovo/0.2.3/rovo/response/type.Result_search= Shows the basic usage of the unwrap method to get the Ok value from a Result, with a note that it panics on Err and is generally discouraged. ```rust let x: Result = Ok(2); assert_eq!(x.unwrap(), 2); ``` ```rust let x: Result = Err("emergency failure"); x.unwrap(); // panics with `emergency failure` ``` -------------------------------- ### MatchedPath Usage Example Source: https://docs.rs/rovo/0.2.3/rovo/extract/struct.MatchedPath_search=std%3A%3Avec Demonstrates how to extract and use the MatchedPath within a route handler. ```APIDOC ## GET /users/{id} ### Description Extracts the matched path of the request within a route handler. ### Method GET ### Endpoint /users/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID parameter in the URL path. #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **MatchedPath** (string) - The string representation of the matched path. #### Response Example ```json { "matched_path": "/users/{id}" } ``` ``` -------------------------------- ### Rust: Create HEAD Request Source: https://docs.rs/rovo/0.2.3/rovo/extract/type.Request_search=std%3A%3Avec Provides an example of creating a HEAD request with a given URI using Request::head(). ```rust let request = Request::head("https://www.rust-lang.org/") .body(()) // Assuming Body is Send + Sync .unwrap(); ``` -------------------------------- ### Axum Example: Construct Query from URI in Rust Source: https://docs.rs/rovo/0.2.3/rovo/extract/struct.Query_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Shows how to use `Query::try_from_uri` to construct a `Query` struct from an `http::Uri`. This is useful for parsing query parameters directly from a given URI. The example deserializes query parameters into an `ExampleParams` struct. ```rust use axum::extract::Query; use http::Uri; use serde::Deserialize; #[derive(Deserialize)] struct ExampleParams { foo: String, bar: u32, } let uri: Uri = "http://example.com/path?foo=hello&bar=42".parse().unwrap(); let result: Query = Query::try_from_uri(&uri).unwrap(); assert_eq!(result.foo, String::from("hello")); assert_eq!(result.bar, 42); ``` -------------------------------- ### Rust Type Signature Search Examples Source: https://docs.rs/rovo/0.2.3/rovo/extract/rejection/struct.FailedToDeserializeFormBody_search= This section provides examples of common search queries for Rust type signatures. These examples illustrate how to search for specific types like `std::vec`, function signatures like `u32 -> bool`, and generic type transformations such as `Option, (T -> U) -> Option`. ```rust * std::vec ``` ```rust * u32 -> bool ``` ```rust * Option, (T -> U) -> Option ``` -------------------------------- ### Rust: Axum Example: Extracting Query Parameters Source: https://docs.rs/rovo/0.2.3/rovo/extract/struct.Query_search=std%3A%3Avec Demonstrates how to use `axum::extract::Query` to deserialize URL query parameters into a `Pagination` struct. The example shows defining the struct, implementing the handler, and setting up the Axum router. It handles query parsing errors by returning a 400 Bad Request. ```Rust use axum::{ extract::Query, routing::get, Router, }; use serde::Deserialize; #[derive(Deserialize)] struct Pagination { page: usize, per_page: usize, } // This will parse query strings like `?page=2&per_page=30` into `Pagination` // structs. async fn list_things(pagination: Query) { let pagination: Pagination = pagination.0; // ... } let app = Router::new().route("/list_things", get(list_things)); ``` -------------------------------- ### Request Builder Methods Source: https://docs.rs/rovo/0.2.3/rovo/extract/type.Request_search= Provides examples of using the `Request` builder to construct requests with specific HTTP methods. ```APIDOC ## GET /request/builder/get ### Description Creates a new `Request` using the GET method. ### Method GET ### Endpoint /request/builder/get ### Parameters #### Query Parameters - **uri** (string) - Required - The URI for the request. ### Request Example ```bash GET /request/builder/get?uri=https://www.rust-lang.org/ ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. #### Response Example ```json { "status": "created" } ``` ``` ```APIDOC ## PUT /request/builder/put ### Description Creates a new `Request` using the PUT method. ### Method PUT ### Endpoint /request/builder/put ### Parameters #### Query Parameters - **uri** (string) - Required - The URI for the request. ### Request Example ```bash PUT /request/builder/put?uri=https://www.rust-lang.org/ ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. #### Response Example ```json { "status": "created" } ``` ``` ```APIDOC ## POST /request/builder/post ### Description Creates a new `Request` using the POST method. ### Method POST ### Endpoint /request/builder/post ### Parameters #### Query Parameters - **uri** (string) - Required - The URI for the request. ### Request Example ```bash POST /request/builder/post?uri=https://www.rust-lang.org/ ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. #### Response Example ```json { "status": "created" } ``` ``` ```APIDOC ## DELETE /request/builder/delete ### Description Creates a new `Request` using the DELETE method. ### Method DELETE ### Endpoint /request/builder/delete ### Parameters #### Query Parameters - **uri** (string) - Required - The URI for the request. ### Request Example ```bash DELETE /request/builder/delete?uri=https://www.rust-lang.org/ ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. #### Response Example ```json { "status": "created" } ``` ``` ```APIDOC ## OPTIONS /request/builder/options ### Description Creates a new `Request` using the OPTIONS method. ### Method OPTIONS ### Endpoint /request/builder/options ### Parameters #### Query Parameters - **uri** (string) - Required - The URI for the request. ### Request Example ```bash OPTIONS /request/builder/options?uri=https://www.rust-lang.org/ ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. #### Response Example ```json { "status": "created" } ``` ``` ```APIDOC ## HEAD /request/builder/head ### Description Creates a new `Request` using the HEAD method. ### Method HEAD ### Endpoint /request/builder/head ### Parameters #### Query Parameters - **uri** (string) - Required - The URI for the request. ### Request Example ```bash HEAD /request/builder/head?uri=https://www.rust-lang.org/ ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. #### Response Example ```json { "status": "created" } ``` ``` ```APIDOC ## CONNECT /request/builder/connect ### Description Creates a new `Request` using the CONNECT method. ### Method CONNECT ### Endpoint /request/builder/connect ### Parameters #### Query Parameters - **uri** (string) - Required - The URI for the request. ### Request Example ```bash CONNECT /request/builder/connect?uri=https://www.rust-lang.org/ ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. #### Response Example ```json { "status": "created" } ``` ``` ```APIDOC ## PATCH /request/builder/patch ### Description Creates a new `Request` using the PATCH method. ### Method PATCH ### Endpoint /request/builder/patch ### Parameters #### Query Parameters - **uri** (string) - Required - The URI for the request. ### Request Example ```bash PATCH /request/builder/patch?uri=https://www.rust-lang.org/ ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. #### Response Example ```json { "status": "created" } ``` ``` ```APIDOC ## TRACE /request/builder/trace ### Description Creates a new `Request` using the TRACE method. ### Method TRACE ### Endpoint /request/builder/trace ### Parameters #### Query Parameters - **uri** (string) - Required - The URI for the request. ### Request Example ```bash TRACE /request/builder/trace?uri=https://www.rust-lang.org/ ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. #### Response Example ```json { "status": "created" } ``` ``` -------------------------------- ### GET /users Source: https://docs.rs/rovo/0.2.3/rovo/extract/struct.OriginalUri_search=u32+-%3E+bool Example of using OriginalUri as an extractor in a GET request to retrieve the original URI. ```APIDOC ## GET /users ### Description This endpoint demonstrates how to extract the original request URI using the `OriginalUri` extractor. It highlights the difference between the stripped `Uri` and the full `original_uri`. ### Method GET ### Endpoint /users ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example Not applicable for this GET request example. ### Response #### Success Response (200) This endpoint does not return a specific response body in the example; it focuses on extractor usage. #### Response Example ```json { "message": "URI extracted successfully" } ``` ## Using OriginalUri in Middleware ### Description This section explains how `OriginalUri` can be accessed from middleware via request extensions, useful for logging or tracing with the full request path. ### Method Any (demonstrated with GET) ### Endpoint /users/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the user. #### Query Parameters None #### Request Body None ### Request Example ```json { "message": "User data" } ``` ### Response #### Success Response (200) - **message** (string) - A confirmation message. #### Response Example ```json { "message": "User data" } ``` ## Tuple Fields ### Description Details about the tuple fields of the `OriginalUri` struct. ### Method N/A ### Endpoint N/A ### Parameters None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ## Methods from Deref ### Description Describes methods inherited from `Deref`, allowing `OriginalUri` to be used like a `Uri`. ### Method N/A ### Endpoint N/A ### Parameters None ### Request Example None ### Response #### Success Response (200) None #### Response Example None #### pub fn path_and_query(&self) -> Option<&PathAndQuery> ##### Description Returns the path and query components of the Uri. ##### Method N/A ##### Endpoint N/A ##### Parameters None ##### Request Example None ##### Response ###### Success Response (200) - **PathAndQuery** (Option<&PathAndQuery>) - The path and query components of the URI. ###### Response Example ```json { "path_and_query": "/hello/world?key=value" } ``` #### pub fn path(&self) -> &str ##### Description Get the path of this `Uri`. Both relative and absolute URIs contain a path component, though it might be the empty string. The path component is case sensitive. ##### Method N/A ##### Endpoint N/A ##### Parameters None ##### Request Example ```rust use http::Uri; let uri: Uri = "/hello/world".parse().unwrap(); assert_eq!(uri.path(), "/hello/world"); ``` ##### Response ###### Success Response (200) - **path** (string) - The path component of the URI. ###### Response Example ```json { "path": "/hello/world" } ``` #### pub fn scheme(&self) -> Option<&Scheme> ##### Description Get the scheme of this `Uri`. Only absolute URIs contain a scheme component. Scheme names are case-insensitive, but the canonical form is lowercase. ##### Method N/A ##### Endpoint N/A ##### Parameters None ##### Request Example ```rust use http::uri::{Scheme, Uri}; let uri: Uri = "http://example.org/hello/world".parse().unwrap(); assert_eq!(uri.scheme(), Some(&Scheme::HTTP)); ``` ##### Response ###### Success Response (200) - **scheme** (Option<&Scheme>) - The scheme of the URI. ###### Response Example ```json { "scheme": "http" } ``` #### pub fn scheme_str(&self) -> Option<&str> ##### Description Get the scheme of this `Uri` as a `&str`. ##### Method N/A ##### Endpoint N/A ##### Parameters None ##### Request Example ```rust let uri: Uri = "http://example.org/hello/world".parse().unwrap(); assert_eq!(uri.scheme_str(), Some("http")); ``` ##### Response ###### Success Response (200) - **scheme_str** (Option<&str>) - The scheme of the URI as a string slice. ###### Response Example ```json { "scheme_str": "http" } ``` #### pub fn authority(&self) -> Option<&Authority> ##### Description Get the authority of this `Uri`. For HTTP, the authority consists of the host and port. The host portion is case-insensitive. The authority also includes a `username:password` component, however, its use is deprecated. ##### Method N/A ##### Endpoint N/A ##### Parameters None ##### Request Example ```rust let uri: Uri = "http://example.org:80/hello/world".parse().unwrap(); assert_eq!(uri.authority().map(|a| a.as_str()), Some("example.org:80")); ``` ##### Response ###### Success Response (200) - **authority** (Option<&Authority>) - The authority component of the URI. ###### Response Example ```json { "authority": "example.org:80" } ``` ``` -------------------------------- ### GET /users/{id} - Get User (Response Example) Source: https://docs.rs/rovo/0.2.3/rovo/extract/struct.Json_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Illustrates using `Json` as a response type to serialize a `User` struct into a JSON response. ```APIDOC ## GET /users/{id} ### Description This endpoint retrieves user information based on the provided user ID and returns it as a JSON object. ### Method GET ### Endpoint /users/{id} #### Path Parameters - **id** (uuid) - Required - The unique identifier of the user. ### Response #### Success Response (200) - **id** (uuid) - The unique identifier of the user. - **username** (string) - The username of the user. ### Response Example ```json { "id": "a1b2c3d4-e5f6-7890-1234-567890abcdef", "username": "john_doe" } ``` ``` -------------------------------- ### GET /users/{id} - Get User (Response Example) Source: https://docs.rs/rovo/0.2.3/rovo/response/struct.Json_search=u32+-%3E+bool Illustrates how to use the `Json` type to serialize a `User` struct into a JSON response. The `Content-Type: application/json` header is automatically set. ```APIDOC ## GET /users/{id} ### Description Retrieves a user by their ID and returns the user details as a JSON response. ### Method GET ### Endpoint /users/:id ### Parameters #### Path Parameters - **id** (uuid) - Required - The unique identifier of the user. ### Response #### Success Response (200 OK) - **id** (uuid) - The unique identifier of the user. - **username** (string) - The username of the user. #### Response Example ```json { "id": "a1b2c3d4-e5f6-7890-1234-567890abcdef", "username": "johndoe" } ``` #### Error Response - **500 Internal Server Error**: If serialization of the `User` struct fails or if a map with non-string keys is used. ``` -------------------------------- ### Get Query String Source: https://docs.rs/rovo/0.2.3/rovo/extract/struct.OriginalUri_search=u32+-%3E+bool Retrieves the query string component of the URI. The query string starts after the '?' and ends before the '#' or the end of the URI. ```APIDOC ## GET /uri/query ### Description Retrieves the query string of this `Uri`, starting after the `?`. ### Method GET ### Endpoint `/uri/query` ### Parameters None ### Request Body None ### Request Example None ### Response #### Success Response (200) - **query** (Option<&str>) - The query string of the URI, or None if not present. #### Response Example ```json { "query": "key=value&foo=bar" } ``` ``` -------------------------------- ### DefaultBodyLimit Example: Different Limits for Different Routes Source: https://docs.rs/rovo/0.2.3/rovo/extract/struct.DefaultBodyLimit_search=u32+-%3E+bool Shows how to apply different body limits to different routes using DefaultBodyLimit. ```APIDOC ## Different limits for different routes `DefaultBodyLimit` can also be selectively applied to have different limits for different routes: ```rust use axum::{ Router, routing::post, body::Body, extract::DefaultBodyLimit, }; let app = Router::new() // this route has a different limit .route("/", post(|request: Request| async {{}}).layer(DefaultBodyLimit::max(1024))) // this route still has the default limit .route("/foo", post(|request: Request| async {{}})); ``` ``` -------------------------------- ### Get URI Query String - Rust Source: https://docs.rs/rovo/0.2.3/rovo/extract/struct.OriginalUri_search=u32+-%3E+bool Retrieves the query string of a URI, which starts after the '?' and is terminated by a '#' or the end of the URI. Returns an Option<&str>. ```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")); ``` ```rust let uri: Uri = "/hello/world".parse().unwrap(); assert!(uri.query().is_none()); ``` -------------------------------- ### Rust Result Iterator Example Source: https://docs.rs/rovo/0.2.3/rovo/response/type.Result_search= Shows how to use the iter method on a Result to get an iterator yielding the contained value if Ok, or nothing if Err. ```rust let x: Result = Ok(7); assert_eq!(x.iter().next(), Some(&7)); let x: Result = Err("nothing!"); assert_eq!(x.iter().next(), None); ``` -------------------------------- ### Access and Modify Request Extensions Source: https://docs.rs/rovo/0.2.3/rovo/extract/type.Request_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Explains how to get and set extensions within a Rust Request. Examples show checking for the presence of an extension and inserting a new one. ```rust let request: Request<()> = Request::default(); assert!(request.extensions().get::().is_none()); let mut request: Request<()> = Request::default(); request.extensions_mut().insert("hello"); assert_eq!(request.extensions().get(), Some(&"hello")); ``` -------------------------------- ### Initialize Rovo Router in Rust Source: https://docs.rs/rovo/0.2.3/rovo/struct.Router_search=std%3A%3Avec Shows the basic initialization of a Rovo Router using the `new()` function. This is the starting point for building a documented API with Rovo. ```rust pub struct Router { /* private fields */ } impl Router where S: Clone + Send + Sync + 'static, { pub fn new() -> Self { // Implementation details } // ... other methods } ``` -------------------------------- ### MockConnectInfo Struct Definition and Usage Example in Rust Source: https://docs.rs/rovo/0.2.3/rovo/extract/connect_info/struct.MockConnectInfo Defines the `MockConnectInfo` struct used for mocking `ConnectInfo` in tests. The example demonstrates its application within an Axum router setup for testing purposes. It highlights the use of `MockConnectInfo` to inject a mock `SocketAddr` and verifies the router's response with a basic test case. ```rust pub struct MockConnectInfo(pub T); use axum::extract::connect_info::{MockConnectInfo, ConnectInfo}; use axum::{Router, body::Body, routing::get, http::{Request, StatusCode}}; use std::net::SocketAddr; use tower::ServiceExt; async fn handler(ConnectInfo(addr): ConnectInfo) {} fn app() -> Router { Router::new().route("/", get(handler)) } fn test_app() -> Router { app().layer(MockConnectInfo(SocketAddr::from(([0, 0, 0, 0], 1337)))) } // #[tokio::test] async fn some_test() { let app = test_app(); let request = Request::new(Body::empty()); let response = app.oneshot(request).await.unwrap(); assert_eq!(response.status(), StatusCode::OK); } ``` -------------------------------- ### Rust Result unwrap_err Method Example Source: https://docs.rs/rovo/0.2.3/rovo/response/type.Result_search= Shows how to use the unwrap_err method to get the Err value from a Result, panicking if the Result is Ok. This is useful for error handling. ```rust let x: Result = Ok(2); x.unwrap_err(); // panics with `2` ``` ```rust let x: Result = Err("emergency failure"); assert_eq!(x.unwrap_err(), "emergency failure"); ``` -------------------------------- ### Rust Result Mutable Iterator Example Source: https://docs.rs/rovo/0.2.3/rovo/response/type.Result_search= Illustrates using the iter_mut method on a mutable Result to get a mutable iterator, allowing modification of the contained value if Ok. ```rust let mut x: Result = Ok(7); match x.iter_mut().next() { Some(v) => *v = 40, None => {}, } assert_eq!(x, Ok(40)); let mut x: Result = Err("nothing!"); assert_eq!(x.iter_mut().next(), None); ``` -------------------------------- ### MockConnectInfo Example Usage in Axum Tests Source: https://docs.rs/rovo/0.2.3/rovo/extract/connect_info/struct.MockConnectInfo_search= Demonstrates how to use MockConnectInfo with an Axum router for testing purposes. It includes setting up a test router and making a request to verify its behavior. ```rust use axum::{ Router, extract::connect_info::{MockConnectInfo, ConnectInfo}, body::Body, routing::get, http::{Request, StatusCode}, }; use std::net::SocketAddr; use tower::ServiceExt; async fn handler(ConnectInfo(addr): ConnectInfo) {} // this router you can run with `app.into_make_service_with_connect_info::()` fn app() -> Router { Router::new().route("/", get(handler)) } // use this router for tests fn test_app() -> Router { app().layer(MockConnectInfo(SocketAddr::from(([0, 0, 0, 0], 1337)))) } // #[tokio::test] async fn some_test() { let app = test_app(); let request = Request::new(Body::empty()); let response = app.oneshot(request).await.unwrap(); assert_eq!(response.status(), StatusCode::OK); } ``` -------------------------------- ### Get Uri Query String - Rust Source: https://docs.rs/rovo/0.2.3/rovo/extract/struct.OriginalUri Retrieves the query string of a Uri, which starts after the '?'. The query component contains non-hierarchical data. Returns None if the Uri does not have a query string. ```rust pub fn query(&self) -> Option<&str> ``` ```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")); ``` ```rust let uri: Uri = "/hello/world".parse().unwrap(); assert!(uri.query().is_none()); ``` -------------------------------- ### Manage Service Readiness and Requests Source: https://docs.rs/rovo/0.2.3/rovo/axum/struct.ApiRouter_search=std%3A%3Avec Provides methods for checking service readiness (`ready`, `ready_oneshot`), executing a single request (`oneshot`), and processing multiple requests from a stream (`call_all`). ```rust fn ready(&mut self) -> Ready<'_, Self, Request> fn ready_oneshot(self) -> ReadyOneshot fn oneshot(self, req: Request) -> Oneshot fn call_all(self, reqs: S) -> CallAll ``` -------------------------------- ### Access and Modify HTTP Request Version Source: https://docs.rs/rovo/0.2.3/rovo/extract/type.Request_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Shows how to get and change the HTTP version associated with a Rust Request. Examples include reading the current version and updating it to a different HTTP version. ```rust let request: Request<()> = Request::default(); assert_eq!(request.version(), Version::HTTP_11); let mut request: Request<()> = Request::default(); *request.version_mut() = Version::HTTP_2; assert_eq!(request.version(), Version::HTTP_2); ``` -------------------------------- ### GET /route Source: https://docs.rs/rovo/0.2.3/rovo/routing/fn.get_search=std%3A%3Avec Creates a GET route with documentation from a `#[rovo]` decorated handler. This function is part of the `rovo::routing` module. ```APIDOC ## GET /route ### Description Create a GET route with documentation from a `#[rovo]` decorated handler. ### Method GET ### Endpoint /route ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "No request body needed for this example." } ``` ### Response #### Success Response (200) - **handler** (IntoApiMethodRouter) - The handler to be used for the route. #### Response Example ```json { "example": "An ApiMethodRouter instance is returned." } ``` ``` -------------------------------- ### GET /rovo/routing Source: https://docs.rs/rovo/0.2.3/rovo/routing/fn.get_search= Creates a GET route using a handler decorated with `#[rovo]`. This function allows defining custom handlers for GET requests. ```APIDOC ## GET /rovo/routing ### Description Creates a GET route with documentation from a `#[rovo]` decorated handler. ### Method GET ### Endpoint /rovo/routing ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json // No request body is typically sent with a GET request. ``` ### Response #### Success Response (200) - **ApiMethodRouter** (object) - Represents the configured API method router for GET requests. #### Response Example ```json // The actual response structure depends on the handler's implementation. // Example placeholder: { "message": "GET route configured successfully" } ``` ``` -------------------------------- ### Define and Configure rovo Router Source: https://docs.rs/rovo/0.2.3/rovo/struct.Router Demonstrates creating a new rovo Router, adding routes, and configuring OpenAPI specifications with default or custom routes. It shows how to integrate with handlers decorated by #[rovo] and finalize the router. ```rust use rovo::{Router, rovo, routing::get, aide::axum::IntoApiResponse}; use rovo::aide::openapi::OpenApi; use rovo::response::Json; #[rovo] async fn documented_handler() -> impl IntoApiResponse { Json(()) } let mut api = OpenApi::default(); api.info.title = "My API".to_string(); // With default OpenAPI routes (/api.json and /api.yaml) let app_default = Router::new() .route("/documented", get(documented_handler)) .with_oas(api.clone()); // With custom OpenAPI base route let app_custom_route = Router::new() .route("/documented", get(documented_handler)) .with_oas_route(api.clone(), "/v1/api"); // Nesting routers let nested_router = Router::new().route("/nested", get(documented_handler)); let app_nested = Router::new() .route("/root", get(documented_handler)) .nest("/sub", nested_router) .with_oas(api.clone()); // Adding state #[derive(Clone, Default)] struct MyState { value: i32 }; let app_with_state = Router::new() .route("/state", get(documented_handler)) .with_state(MyState::default()); // Finalizing the API let finalized_app = app_with_state.finish(); let finalized_app_with_api = app_with_state.finish_api(&mut api); let finalized_app_with_extension = app_with_state.finish_api_with_extension(api); // Converting to underlying aide::ApiRouter let aide_router = app_with_state.into_inner(); ``` -------------------------------- ### Rust: Create OPTIONS Request Source: https://docs.rs/rovo/0.2.3/rovo/extract/type.Request_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Shows how to create an HTTP OPTIONS request using the `Request::options()` convenience method in Rust. This method initializes the builder with the OPTIONS method and a specified URI. ```rust let request = Request::options("https://www.rust-lang.org/") .body(()) .unwrap(); ``` -------------------------------- ### Get Service When Ready Source: https://docs.rs/rovo/0.2.3/rovo/extract/connect_info/struct.IntoMakeServiceWithConnectInfo Provides methods to obtain a reference to the service when it's ready to accept requests. `ready` yields a mutable reference, while `ready_oneshot` yields ownership of the service once it's ready. Both are crucial for asynchronous service operations. ```rust fn ready(&mut self) -> Ready<'_, Self, Request> where Self: Sized, Yields a mutable reference to the service when it is ready to accept a request. Source§ ``` ```rust fn ready_oneshot(self) -> ReadyOneshot where Self: Sized, Yields the service when it is ready to accept a request. Source§ ``` -------------------------------- ### fn ready(&mut self) -> Ready<'_, Self, Request> Source: https://docs.rs/rovo/0.2.3/rovo/axum/struct.ApiRouter_search=u32+-%3E+bool Provides a mutable reference to the service when it is ready to accept a request. ```APIDOC ## fn ready(&mut self) -> Ready<'_, Self, Request> ### Description Yields a mutable reference to the service when it is ready to accept a request. ### Method GET ### Endpoint /websites/rs_rovo_0_2_3_rovo/ready ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **self** (type) - A mutable reference to the service. ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (200) - **Ready<'_, Self, Request>** (type) - A future that resolves to a mutable reference to the service. #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### POST /users - Create User (Extractor Example) Source: https://docs.rs/rovo/0.2.3/rovo/extract/struct.Json_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates using `extract::Json` to deserialize a JSON request body into a `CreateUser` struct. ```APIDOC ## POST /users ### Description This endpoint accepts a JSON payload to create a new user. ### Method POST ### Endpoint /users #### Request Body - **email** (string) - Required - The email address of the user. - **password** (string) - Required - The password for the user. ### Request Example ```json { "email": "test@example.com", "password": "securepassword" } ``` ### Response #### Success Response (200) (No specific success response body is detailed in the example, but typically would indicate creation success). #### Response Example (No specific success response body is detailed in the example.) ``` -------------------------------- ### Extracting Path Parameters into a HashMap (Rust) Source: https://docs.rs/rovo/0.2.3/rovo/extract/struct.Path_search= This example shows how to capture all available path parameters into a `HashMap`. This is useful when the exact path parameters are not known in advance or when you need to process them dynamically. The keys of the HashMap will be the parameter names, and the values will be their string representations. ```Rust use axum::extract::Path; use axum::routing::get; use axum::Router; use std::collections::HashMap; async fn params_map(Path(params): Path>) { // ... } let app = Router::new().route("/users/{user_id}/team/{team_id}", get(params_map)); ``` -------------------------------- ### GET /route Source: https://docs.rs/rovo/0.2.3/rovo/routing/fn.get_search=u32+-%3E+bool Defines a GET route using a handler function. The handler can extract information from the request. ```APIDOC ## GET /route ### Description Creates a GET route with documentation from a `#[rovo]` decorated handler. This function allows defining how to handle incoming GET requests and extract parameters. ### Method GET ### Endpoint `/route` (or a custom endpoint defined by the handler) ### Parameters #### Request Body This endpoint does not typically use a request body for GET requests. ### Request Example (GET requests usually do not have a body. Parameters are typically in query or path.) ### Response #### Success Response (200) - **Type**: Depends on the return type of the handler `H`. - **Description**: The response content generated by the handler. #### Response Example ```json { "message": "Success!" } ``` ### Error Handling - **Type**: `rovo::extract::path::ErrorKind` or other error types defined by the handler. - **Description**: Errors can occur during parameter extraction or handler execution. ``` -------------------------------- ### Rust: Create Request with Builder Source: https://docs.rs/rovo/0.2.3/rovo/extract/type.Request_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates creating an HTTP request using the `Request::builder()` pattern in Rust. This allows for step-by-step configuration of method, URI, headers, and body. ```rust let request = Request::builder() .method("GET") .uri("https://www.rust-lang.org/") .header("X-Custom-Foo", "Bar") .body(()) .unwrap(); ``` -------------------------------- ### Chain GET Handler with ApiMethodRouter in Rust Source: https://docs.rs/rovo/0.2.3/rovo/struct.ApiMethodRouter This method facilitates chaining a GET handler to the `ApiMethodRouter`. The handler must implement `IntoApiMethodRouter`, ensuring it can be integrated into rovo's routing workflow. This allows for the sequential definition of routes handling GET requests. ```rust pub fn get(self, handler: H) -> Self where H: IntoApiMethodRouter ```