### HTTPS GET Request with Reqwless and esp-mbedtls (Rust) Source: https://docs.rs/reqwless/0.14.0/index Illustrates setting up and performing an HTTPS GET request using reqwless with the esp-mbedtls TLS backend. This example highlights the TLS configuration, including CA certificates and hardware acceleration for RSA, and sending a request with custom headers. ```rust /// ... [initialization code. See esp-wifi] let state = TcpClientState::<1, 4096, 4096>::new(); let mut tcp_client = TcpClient::new(stack, &state); let dns_socket = DnsSocket::new(&stack); let mut rsa = Rsa::new(peripherals.RSA); let config = TlsConfig::new( reqwless::TlsVersion::Tls1_3, reqwless::Certificates { ca_chain: reqwless::X509::pem(CERT.as_bytes()).ok(), ..Default::default() }, Some(&mut rsa), // Will use hardware acceleration ); let mut client = HttpClient::new_with_tls(&tcp_client, &dns_socket, config); let mut request = client .request(reqwless::request::Method::GET, "https://www.google.com") .await .unwrap() .content_type(reqwless::headers::ContentType::TextPlain) .headers(&[("Host", "google.com")]) .send(&mut buffer) .await .unwrap(); ``` -------------------------------- ### TLS 1.3 HTTPS GET Request with esp-mbedtls and Hardware Acceleration (Rust) Source: https://docs.rs/reqwless/0.14.0/reqwless/index_search= Illustrates setting up and performing an HTTPS GET request using reqwless with esp-mbedtls for TLS 1.3 and hardware acceleration via the RSA peripheral. This example requires specific ESP32 board configurations and involves setting up TCP client, DNS socket, and TLS configuration. It targets 'https://www.google.com'. ```rust /// ... [initialization code. See esp-wifi] let state = TcpClientState::<1, 4096, 4096>::new(); let mut tcp_client = TcpClient::new(stack, &state); let dns_socket = DnsSocket::new(&stack); let mut rsa = Rsa::new(peripherals.RSA); let config = TlsConfig::new( reqwless::TlsVersion::Tls1_3, reqwless::Certificates { ca_chain: reqwless::X509::pem(CERT.as_bytes()).ok(), ..Default::default() }, Some(&mut rsa), // Will use hardware acceleration ); let mut client = HttpClient::new_with_tls(&tcp_client, &dns_socket, config); let mut request = client .request(reqwless::request::Method::GET, "https://www.google.com") .await .unwrap() .content_type(reqwless::headers::ContentType::TextPlain) .headers(&[("Host", "google.com")]) .send(&mut buffer) .await .unwrap(); ``` -------------------------------- ### HttpResource Methods Source: https://docs.rs/reqwless/0.14.0/src/reqwless/client.rs_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Provides methods to create and configure HTTP requests for different methods (GET, POST, PUT, DELETE, HEAD) and to send requests. ```APIDOC ## HttpResource Methods ### Description Provides methods to create and configure HTTP requests for different methods (GET, POST, PUT, DELETE, HEAD) and to send requests. ### Methods #### `request` - **Description**: Creates a new HTTP request builder with the specified method and path. - **Method**: `request` - **Endpoint**: N/A (Method on `HttpResource` struct) - **Parameters**: - **`method`** (Method) - Required - The HTTP method for the request. - **`path`** (string) - Required - The path for the request. - **Response**: - **Success Response (200)**: `HttpResourceRequestBuilder` for further configuration. #### `get` - **Description**: Creates a new scoped GET http request. - **Method**: `get` - **Endpoint**: N/A (Method on `HttpResource` struct) - **Parameters**: - **`path`** (string) - Required - The path for the GET request. - **Response**: - **Success Response (200)**: `HttpResourceRequestBuilder` for further configuration. #### `post` - **Description**: Creates a new scoped POST http request. - **Method**: `post` - **Endpoint**: N/A (Method on `HttpResource` struct) - **Parameters**: - **`path`** (string) - Required - The path for the POST request. - **Response**: - **Success Response (200)**: `HttpResourceRequestBuilder` for further configuration. #### `put` - **Description**: Creates a new scoped PUT http request. - **Method**: `put` - **Endpoint**: N/A (Method on `HttpResource` struct) - **Parameters**: - **`path`** (string) - Required - The path for the PUT request. - **Response**: - **Success Response (200)**: `HttpResourceRequestBuilder` for further configuration. #### `delete` - **Description**: Creates a new scoped DELETE http request. - **Method**: `delete` - **Endpoint**: N/A (Method on `HttpResource` struct) - **Parameters**: - **`path`** (string) - Required - The path for the DELETE request. - **Response**: - **Success Response (200)**: `HttpResourceRequestBuilder` for further configuration. #### `head` - **Description**: Creates a new scoped HEAD http request. - **Method**: `head` - **Endpoint**: N/A (Method on `HttpResource` struct) - **Parameters**: - **`path`** (string) - Required - The path for the HEAD request. - **Response**: - **Success Response (200)**: `HttpResourceRequestBuilder` for further configuration. #### `send` - **Description**: Sends a request to a resource. The base path of the resource is prepended to the request path. The response headers are stored in the provided rx_buf. The response is returned. - **Method**: `send` - **Endpoint**: N/A (Method on `HttpResource` struct) - **Parameters**: - **`request`** (Request) - Required - The request object to send. - **`rx_buf`** (&mut [u8]) - Required - A mutable buffer to store response headers. - **Response**: - **Success Response (200)**: `Result>, Error>` - The response from the server or an error. ``` -------------------------------- ### HttpResource Methods Source: https://docs.rs/reqwless/0.14.0/src/reqwless/client.rs_search= Provides methods to create and configure HTTP requests for different methods (GET, POST, PUT, DELETE, HEAD) on a specific resource. ```APIDOC ## HttpResource Methods ### Description These methods facilitate the creation of HTTP requests for a specific resource. They allow you to specify the HTTP method and the path for the request, returning a builder to further configure the request. ### Methods - `get(path: &'req str)`: Creates a GET request. - `post(path: &'req str)`: Creates a POST request. - `put(path: &'req str)`: Creates a PUT request. - `delete(path: &'req str)`: Creates a DELETE request. - `head(path: &'req str)`: Creates a HEAD request. ### Endpoint These methods operate on a base path defined by the `HttpResource`. ### Parameters - `path` (string): The specific endpoint path for the request relative to the resource's base path. ### Request Body Not directly applicable to the method creation, but the returned builder will handle request bodies. ### Response Returns an `HttpResourceRequestBuilder` which can be used to further configure and send the request. ``` -------------------------------- ### Basic HTTP POST Request with Reqwless Client API (Rust) Source: https://docs.rs/reqwless/0.14.0/index Demonstrates constructing and sending a basic HTTP POST request using the higher-level client API of the reqwless crate. This example assumes a `TokioTcp` transport and `StaticDns` resolver, and shows how to set the URL, request body, content type, and send the request. ```rust let url = format!("http://localhost:{}", addr.port()); let mut client = HttpClient::new(TokioTcp, StaticDns); // Types implementing embedded-nal-async let mut rx_buf = [0; 4096]; let response = client .request(Method::POST, &url) .await .unwrap() .body(b"PING") .content_type(ContentType::TextPlain) .send(&mut rx_buf) .await .unwrap(); ``` -------------------------------- ### Implement HttpResource Methods in Rust Source: https://docs.rs/reqwless/0.14.0/reqwless/client/struct.HttpResource_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Provides implementations for HttpResource, including methods to create buffered resources, initiate requests with various HTTP methods (GET, POST, PUT, DELETE, HEAD), and send requests with a specified body and receive a response. ```rust pub fn into_buffered<'buf>( self, tx_buf: &'buf mut [u8], ) -> HttpResource<'buf, C> where 'res: 'buf, { // ... implementation ... } ``` ```rust pub fn request<'req>( &'req mut self, method: Method, path: &'req str, ) -> HttpResourceRequestBuilder<'req, 'res, C, ()> ``` ```rust pub fn get<'req>( &'req mut self, path: &'req str, ) -> HttpResourceRequestBuilder<'req, 'res, C, ()> ``` ```rust pub fn post<'req>( &'req mut self, path: &'req str, ) -> HttpResourceRequestBuilder<'req, 'res, C, ()> ``` ```rust pub fn put<'req>( &'req mut self, path: &'req str, ) -> HttpResourceRequestBuilder<'req, 'res, C, ()> ``` ```rust pub fn delete<'req>( &'req mut self, path: &'req str, ) -> HttpResourceRequestBuilder<'req, 'res, C, ()> ``` ```rust pub fn head<'req>( &'req mut self, path: &'req str, ) -> HttpResourceRequestBuilder<'req, 'res, C, ()> ``` ```rust pub async fn send<'req, 'buf, B: RequestBody>( &'req mut self, request: Request<'req, B>, rx_buf: &'buf mut [u8], ) -> Result>, Error> ``` -------------------------------- ### Create HTTP Requests with reqwless in Rust Source: https://docs.rs/reqwless/0.14.0/reqwless/request/struct.Request_search= Provides functions to create new HTTP requests using the `reqwless` library in Rust. These functions abstract the creation of `DefaultRequestBuilder` instances for various HTTP methods like GET, POST, PUT, DELETE, etc., simplifying request setup. ```rust pub fn new(method: Method, path: &'req str) -> DefaultRequestBuilder<'req, ()> ``` ```rust pub fn get(path: &'req str) -> DefaultRequestBuilder<'req, ()> ``` ```rust pub fn post(path: &'req str) -> DefaultRequestBuilder<'req, ()> ``` ```rust pub fn put(path: &'req str) -> DefaultRequestBuilder<'req, ()> ``` ```rust pub fn delete(path: &'req str) -> DefaultRequestBuilder<'req, ()> ``` ```rust pub fn head(path: &'req str) -> DefaultRequestBuilder<'req, ()> ``` ```rust pub fn patch(path: &'req str) -> DefaultRequestBuilder<'req, ()> ``` ```rust pub fn options(path: &'req str) -> DefaultRequestBuilder<'req, ()> ``` ```rust pub fn connect(path: &'req str) -> DefaultRequestBuilder<'req, ()> ``` ```rust pub fn trace(path: &'req str) -> DefaultRequestBuilder<'req, ()> ``` -------------------------------- ### Initiate HTTP Request Builder in Rust Source: https://docs.rs/reqwless/0.14.0/src/reqwless/client.rs_search= The `request` method on `HttpResource` starts the process of building a new HTTP request. It takes the HTTP method and path, returning an `HttpResourceRequestBuilder`. This builder can then be chained with other methods to configure the request further. ```rust pub fn request<'req>( &'req mut self, method: Method, path: &'req str, ) -> HttpResourceRequestBuilder<'req, 'res, C, ()> { HttpResourceRequestBuilder { conn: &mut self.conn, request: Request::new(method, path).host(self.host), base_path: self.base_path, } } ``` -------------------------------- ### Create Specific HTTP Method Requests in Rust Source: https://docs.rs/reqwless/0.14.0/reqwless/request/struct.Request_search=u32+-%3E+bool Offers convenient functions for creating HTTP requests with specific methods like GET, POST, PUT, DELETE, HEAD, PATCH, OPTIONS, CONNECT, and TRACE. Each function takes a path and returns a `DefaultRequestBuilder` pre-configured with the corresponding HTTP method. ```rust pub fn get(path: &'req str) -> DefaultRequestBuilder<'req, ()> ``` ```rust pub fn post(path: &'req str) -> DefaultRequestBuilder<'req, ()> ``` ```rust pub fn put(path: &'req str) -> DefaultRequestBuilder<'req, ()> ``` ```rust pub fn delete(path: &'req str) -> DefaultRequestBuilder<'req, ()> ``` ```rust pub fn head(path: &'req str) -> DefaultRequestBuilder<'req, ()> ``` ```rust pub fn patch(path: &'req str) -> DefaultRequestBuilder<'req, ()> ``` ```rust pub fn options(path: &'req str) -> DefaultRequestBuilder<'req, ()> ``` ```rust pub fn connect(path: &'req str) -> DefaultRequestBuilder<'req, ()> ``` ```rust pub fn trace(path: &'req str) -> DefaultRequestBuilder<'req, ()> ``` -------------------------------- ### Basic Authentication Header Generation (Rust) Source: https://docs.rs/reqwless/0.14.0/src/reqwless/request.rs_search= Demonstrates how to construct an HTTP GET request with Basic Authentication. It builds a request, adds credentials, writes the header to a buffer, and asserts the resulting header format, including the Base64 encoded credentials. ```rust #[tokio::test] async fn basic_auth() { let mut buffer: Vec = Vec::new(); Request::new(Method::GET, "/") .basic_auth("username", "password") .build() .write_header(&mut buffer) .await .unwrap(); assert_eq!( b"GET / HTTP/1.1\r\nAuthorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ9\r\n\r\n", buffer.as_slice() ); } ``` -------------------------------- ### Create Scoped GET Request in Rust Source: https://docs.rs/reqwless/0.14.0/src/reqwless/client.rs_search= The `get` method is a convenience function on `HttpResource` for creating a GET request. It takes a path and returns an `HttpResourceRequestBuilder` pre-configured with the `Method::GET`. This simplifies initiating GET requests to a specific resource path. ```rust pub fn get<'req>(&'req mut self, path: &'req str) -> HttpResourceRequestBuilder<'req, 'res, C, ()> { self.request(Method::GET, path) } ``` -------------------------------- ### HTTP Request Creation Source: https://docs.rs/reqwless/0.14.0/reqwless/request/struct.Request_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E This section covers the creation of various HTTP requests using the reqwless library. It includes methods for common HTTP verbs like GET, POST, PUT, DELETE, and more. ```APIDOC ## POST /api/users ### Description Creates a new user resource. ### Method POST ### Endpoint /api/users ### Parameters #### Request Body - **username** (string) - Required - The desired username. - **email** (string) - Required - The user's email address. ### Request Example ```json { "username": "johndoe", "email": "john.doe@example.com" } ``` ### Response #### Success Response (201) - **id** (string) - The unique identifier for the newly created user. - **message** (string) - A confirmation message. #### Response Example ```json { "id": "user-12345", "message": "User created successfully." } ``` ``` ```APIDOC ## GET /api/users/{userId} ### Description Retrieves a specific user resource by their ID. ### Method GET ### Endpoint /api/users/{userId} ### Parameters #### Path Parameters - **userId** (string) - Required - The ID of the user to retrieve. ### Response #### Success Response (200) - **id** (string) - The unique identifier for the user. - **username** (string) - The user's username. - **email** (string) - The user's email address. #### Response Example ```json { "id": "user-12345", "username": "johndoe", "email": "john.doe@example.com" } ``` ``` ```APIDOC ## PUT /api/users/{userId} ### Description Updates an existing user resource. ### Method PUT ### Endpoint /api/users/{userId} ### Parameters #### Path Parameters - **userId** (string) - Required - The ID of the user to update. #### Request Body - **email** (string) - Optional - The updated email address for the user. ### Request Example ```json { "email": "john.doe.updated@example.com" } ``` ### Response #### Success Response (200) - **message** (string) - A confirmation message indicating the user was updated. #### Response Example ```json { "message": "User updated successfully." } ``` ``` ```APIDOC ## DELETE /api/users/{userId} ### Description Deletes a specific user resource by their ID. ### Method DELETE ### Endpoint /api/users/{userId} ### Parameters #### Path Parameters - **userId** (string) - Required - The ID of the user to delete. ### Response #### Success Response (204) No content is returned upon successful deletion. #### Response Example (No content) ``` ```APIDOC ## Request Construction Examples ### Description Examples of constructing different HTTP requests using the `reqwless::request` module. ### Method Various (GET, POST, PUT, DELETE, etc.) ### Endpoint N/A (Illustrative) ### Code Examples **Creating a GET request:** ```rust use reqwless::request; let get_request = request::Request::get("/items"); ``` **Creating a POST request with a body:** ```rust use reqwless::request; use reqwless::request::RequestBody; struct MyBody { /* ... */ } impl RequestBody for MyBody { /* ... */ } let post_request = request::Request::post("/items", MyBody { /* ... */ }); ``` **Creating a request with a specific method and path:** ```rust use reqwless::request; use reqwless::Method; let custom_request = request::Request::new(Method::PUT, "/items/123"); ``` ``` -------------------------------- ### Create New HttpClient Instance Source: https://docs.rs/reqwless/0.14.0/reqwless/client/struct.HttpClient Provides methods to instantiate an HttpClient. `new` creates a client with basic connection and DNS capabilities, while `new_with_tls` adds TLS configuration for secure connections. ```rust pub fn new(client: &'a T, dns: &'a D) -> Self ``` ```rust pub fn new_with_tls(client: &'a T, dns: &'a D, tls: TlsConfig<'a>) -> Self ``` -------------------------------- ### Get String Representation of ContentType in Rust Source: https://docs.rs/reqwless/0.14.0/reqwless/headers/enum.ContentType Implements the as_str method for the ContentType enum. This method returns the string representation of the enum variant, which is useful for setting HTTP headers or logging. For example, ContentType::TextHtml would return "text/html". ```rust impl ContentType { pub fn as_str(&self) -> &str { match self { ContentType::TextHtml => "text/html", ContentType::TextPlain => "text/plain", ContentType::ApplicationJson => "application/json", ContentType::ApplicationCbor => "application/cbor", ContentType::ApplicationOctetStream => "application/octet-stream", } } } ``` -------------------------------- ### TlsConfig Constructor Source: https://docs.rs/reqwless/0.14.0/reqwless/client/struct.TlsConfig Initializes a new TlsConfig with the provided seed, read buffer, write buffer, and TLS verification settings. ```APIDOC ## `TlsConfig::new` ### Description Initializes a new `TlsConfig` with the provided seed, read buffer, write buffer, and TLS verification settings. ### Method `pub fn new` ### Endpoint `reqwless::client::TlsConfig::new` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust // This is a conceptual example as TlsConfig is a struct and not directly called via an endpoint. // Actual usage would involve passing TlsConfig to a client constructor or configuration. // Example parameters (replace with actual values and types) let seed: u64 = 12345; let mut read_buffer: Vec = vec![0; 1024]; let mut write_buffer: Vec = vec![0; 1024]; // Assuming TlsVerify is a defined type // let verify: TlsVerify = TlsVerify::new(...); // let tls_config = TlsConfig::new(seed, &mut read_buffer, &mut write_buffer, verify); ``` ### Response #### Success Response (200) Returns a `TlsConfig` instance. #### Response Example ```json // TlsConfig is a struct, its representation is internal and not directly serializable as JSON. // The constructor returns an instance of the struct. ``` ``` -------------------------------- ### Get Type ID of a Value (Rust) Source: https://docs.rs/reqwless/0.14.0/reqwless/response/struct.HeaderIterator_search=std%3A%3Avec Gets the `TypeId` of the current value. This is useful for runtime type identification and is part of the `Any` trait implementation. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### HttpClient Request Methods Source: https://docs.rs/reqwless/0.14.0/reqwless/client/struct.HttpClient Details the methods for initiating HTTP requests and handling resources using the HttpClient. ```APIDOC ## HttpClient Request Methods ### `request` Creates a single HTTP request. #### Method `pub async fn request<'conn>( &'conn mut self, method: Method, url: &'conn str, ) -> Result, ()>, Error>` #### Parameters - **method** (`Method`): The HTTP method for the request (e.g., GET, POST). - **url** (`&'conn str`): The URL for the HTTP request. #### Response - **Success Response (Result)**: Returns an `HttpRequestHandle` on success, allowing further manipulation of the request. - **Error Response (Result)**: Returns an `Error` if the request cannot be initiated. ``` ```APIDOC ### `resource` Creates a connection to a server with the provided `resource_url`. The path in the url is considered the base path for subsequent requests. #### Method `pub async fn resource<'res>( &'res mut self, resource_url: &'res str, ) -> Result>, Error>` #### Parameters - **resource_url** (`&'res str`): The URL of the resource to connect to. #### Response - **Success Response (Result)**: Returns an `HttpResource` on success, which can be used for subsequent requests to the same base path. - **Error Response (Result)**: Returns an `Error` if the connection to the resource cannot be established. ``` -------------------------------- ### Create HTTP Resource Connection Source: https://docs.rs/reqwless/0.14.0/src/reqwless/client.rs_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Establishes a connection to a server using a provided resource URL. The URL's path is set as the base path for subsequent requests. This function parses the URL and initiates the connection process. ```rust pub async fn resource<'res>( &'res mut self, resource_url: &'res str, ) -> Result>, Error> { let resource_url = Url::parse(resource_url)?; let conn = self.connect(&resource_url).await?; Ok(HttpResource { conn, host: resource_url.host(), base_path: resource_url.path(), }) } ``` -------------------------------- ### Create GET Request - Rust Source: https://docs.rs/reqwless/0.14.0/reqwless/client/struct.HttpResource Creates a new scoped GET HTTP request for an HttpResource. This method takes a mutable reference to self and a path string, returning a HttpResourceRequestBuilder to further configure the request. ```rust pub fn get<'req>( &'req mut self, path: &'req str, ) -> HttpResourceRequestBuilder<'req, 'res, C, ()> ``` -------------------------------- ### Connect to a URL Source: https://docs.rs/reqwless/0.14.0/src/reqwless/client.rs_search=u32+-%3E+bool Establishes an HTTP or HTTPS connection to a given URL. It handles DNS resolution and TLS negotiation for HTTPS connections. ```APIDOC ## POST /connect ### Description Establishes an HTTP or HTTPS connection to a given URL. It handles DNS resolution and TLS negotiation for HTTPS connections. ### Method POST ### Endpoint /connect ### Parameters #### Query Parameters - **url** (string) - Required - The URL to connect to. ### Request Body ```json { "url": "http://example.com" } ``` ### Response #### Success Response (200) - **connection_id** (string) - A unique identifier for the established connection. #### Response Example ```json { "connection_id": "conn_12345" } ``` ``` -------------------------------- ### Get String Representation of ContentType in Rust Source: https://docs.rs/reqwless/0.14.0/reqwless/headers/enum.ContentType_search= Provides a method `as_str` for the ContentType enum to get its string representation. This is useful for setting the 'Content-Type' header in HTTP requests or for logging and debugging purposes. The method returns a static string slice corresponding to the enum variant. ```Rust pub fn as_str(&self) -> &str { // Implementation details for conversion to string } ``` -------------------------------- ### Get Response Body in Rust Source: https://docs.rs/reqwless/0.14.0/reqwless/response/struct.Response_search= A method `body` for the `Response` struct that returns the response body. This provides access to the content of the HTTP response. ```rust pub fn body(self) -> ResponseBody<'resp, 'buf, C> ``` -------------------------------- ### Test TLS 1.3 Server Connection with OpenSSL Source: https://docs.rs/reqwless/0.14.0/reqwless/index_search= This snippet demonstrates how to test a server's TLS 1.3 compatibility and supported cipher suites using the OpenSSL command-line tool. It includes commands for testing with a limited set of signature algorithms and a fallback option. ```bash openssl s_client -tls1_3 -ciphersuites TLS_AES_128_GCM_SHA256 -sigalgs "ECDSA+SHA256:ECDSA+SHA384:ed25519" -connect hostname:443 ``` ```bash openssl s_client -tls1_3 -ciphersuites TLS_AES_128_GCM_SHA256 -connect hostname:443 ``` -------------------------------- ### Writing Request Headers Source: https://docs.rs/reqwless/0.14.0/reqwless/request/struct.Request_search= Demonstrates how to write the request headers to an I/O stream. ```APIDOC ## Write Request Header ### Description This method writes the HTTP request header to a provided I/O stream. ### Method `write_header` ### Endpoint N/A (This is a method on an existing `Request` object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Parameters for `write_header` - **c** (&mut C) - Required - A mutable reference to a type implementing the `Write` trait, where the header will be written. ### Request Example ```rust use std::io::Cursor; use reqwless::request::Request; let request: Request<'_, ()> = Request::get("/data"); let mut buffer = Cursor::new(Vec::new()); match request.write_header(&mut buffer) { Ok(_) => { // Header written successfully let header_bytes = buffer.into_inner(); println!("Header written: {:?}", String::from_utf8_lossy(&header_bytes)); } Err(e) => { eprintln!("Error writing header: {}", e); } } ``` ### Response #### Success Response (Result<(), Error>) - **Ok(())** - Indicates the header was written successfully. #### Error Response (Result<(), Error>) - **Err(Error)** - An error occurred during the writing process. ``` -------------------------------- ### Blanket Implementations for Generic Types - Rust Source: https://docs.rs/reqwless/0.14.0/reqwless/client/struct.HttpClient_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates blanket implementations for generic types applied to HttpClient, such as `Any`, `Borrow`, `BorrowMut`, `From`, `Into`, `Same`, `TryFrom`, `TryInto`, and `VZip`. These implementations enable various standard Rust functionalities and conversions. ```rust impl Any for T where T: 'static + ?Sized, impl Borrow for T where T: ?Sized, impl BorrowMut for T where T: ?Sized, impl From for T impl Into for T where U: From, impl Same for T impl TryFrom for T where U: Into, impl TryInto for T where U: TryFrom, impl VZip for T where V: MultiLane, ``` -------------------------------- ### Implement ResponseBody Methods Source: https://docs.rs/reqwless/0.14.0/reqwless/response/struct.ResponseBody_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Provides implementations for the ResponseBody struct. Includes a method to get a BodyReader and asynchronous methods to read the entire body into a buffer or discard it. ```rust impl<'resp, 'buf, C> ResponseBody<'resp, 'buf, C> where C: Read, { pub fn reader(self) -> BodyReader> } ``` ```rust impl<'resp, 'buf, C> ResponseBody<'resp, 'buf, C> where C: Read + TryBufRead, { pub async fn read_to_end(self) -> Result<&'buf mut [u8], Error> pub async fn discard(self) -> Result } ``` -------------------------------- ### Get Response Headers in Rust Source: https://docs.rs/reqwless/0.14.0/reqwless/response/struct.Response_search= A method `headers` for the `Response` struct that returns an iterator over the response headers. This allows for easy access and processing of header information. ```rust pub fn headers(&self) -> HeaderIterator<'_> ``` -------------------------------- ### Accumulating Iterator Values: fold Source: https://docs.rs/reqwless/0.14.0/reqwless/response/struct.HeaderIterator_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E The `fold` method consumes an iterator and applies a closure to accumulate a single value. It starts with an initial value and updates it with each element processed. ```rust fn fold(self, init: B, f: F) -> B where Self: Sized, F: FnMut(B, Self::Item) -> B; ``` -------------------------------- ### Implement ResponseBody Methods Source: https://docs.rs/reqwless/0.14.0/reqwless/response/struct.ResponseBody_search=std%3A%3Avec Provides implementations for the ResponseBody struct. Includes a method to get a BodyReader and asynchronous methods to read the entire body into a buffer or discard it. ```Rust impl<'resp, 'buf, C> ResponseBody<'resp, 'buf, C> where C: Read, { pub fn reader(self) -> BodyReader> } impl<'resp, 'buf, C> ResponseBody<'resp, 'buf, C> where C: Read + TryBufRead, { pub async fn read_to_end(self) -> Result<&'buf mut [u8], Error> pub async fn discard(self) -> Result } ``` -------------------------------- ### Async HTTP Client Initialization with TLS (Rust) Source: https://docs.rs/reqwless/0.14.0/src/reqwless/client.rs Initializes an asynchronous HTTP client with TLS support. Requires a TCP connection, DNS resolution, and a TLS configuration object. This is used for secure HTTP connections. ```rust #[cfg(any(feature = "embedded-tls", feature = "esp-mbedtls"))] pub fn new_with_tls(client: &'a T, dns: &'a D, tls: TlsConfig<'a>) -> Self { Self { client, dns, tls: Some(tls), } } } // ... TlsConfig struct definitions ``` -------------------------------- ### RequestBody Trait Source: https://docs.rs/reqwless/0.14.0/reqwless/request/trait.RequestBody The RequestBody trait defines how to write the request body to a writer. It includes required and provided methods for writing and getting the body's length. ```APIDOC ## Trait RequestBody ### Description The request body ### Required Methods #### async fn write(&self, writer: &mut W) -> Result<(), W::Error> Write the body to the provided writer ### Provided Methods #### fn len(&self) -> Option Get the length of the body if known If the length is known, then it will be written in the `Content-Length` header, chunked encoding will be used otherwise. ### Dyn Compatibility This trait is **not** dyn compatible. _In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe._ ### Implementations on Foreign Types #### impl RequestBody for &[u8] #### impl RequestBody for () #### impl RequestBody for Option where T: RequestBody ``` -------------------------------- ### Mock Read/Write Implementation for Testing (Rust) Source: https://docs.rs/reqwless/0.14.0/src/reqwless/client.rs_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Provides a mock implementation of Read and Write traits using a Vec buffer for testing purposes. This allows simulating network I/O without actual network connections. It includes a default implementation and specific async read/write methods. ```rust struct VecBuffer(Vec); impl ErrorType for VecBuffer { type Error = Infallible; } impl Read for VecBuffer { async fn read(&mut self, _buf: &mut [u8]) -> Result { unreachable!() } } impl Write for VecBuffer { async fn write(&mut self, buf: &[u8]) -> Result { self.0.extend_from_slice(buf); Ok(buf.len()) } async fn flush(&mut self) -> Result<(), Self::Error> { self.0.flush().await } } ``` -------------------------------- ### Test: Get Number of Hex Characters Source: https://docs.rs/reqwless/0.14.0/src/reqwless/body_writer/buffering_chunked.rs_search= Unit tests for the `get_num_hex_chars` function, verifying its correctness for various input values including zero and values that span different hexadecimal digit counts. ```Rust #[test] fn can_get_hex_chars() { assert_eq!(1, get_num_hex_chars(0)); assert_eq!(1, get_num_hex_chars(1)); assert_eq!(1, get_num_hex_chars(0xF)); assert_eq!(2, get_num_hex_chars(0x10)); assert_eq!(2, get_num_hex_chars(0xFF)); assert_eq!(3, get_num_hex_chars(0x100)); } ``` -------------------------------- ### Get string representation of ContentType in Rust Source: https://docs.rs/reqwless/0.14.0/reqwless/headers/enum.ContentType_search=std%3A%3Avec Provides the `as_str` method for the `ContentType` enum. This method returns the string slice representation of the enum variant, which is useful for setting HTTP headers or logging. ```Rust pub fn as_str(&self) -> &str { // Implementation details would go here to return the string slice for each variant } ``` -------------------------------- ### Perform HTTP Requests with HttpClient Source: https://docs.rs/reqwless/0.14.0/reqwless/client/struct.HttpClient Enables making HTTP requests using the HttpClient. `request` is used for general HTTP requests with a specified method and URL, while `resource` establishes a connection to a server based on a URL, setting it as the base path for subsequent requests. ```rust pub async fn request<'conn>( &'conn mut self, method: Method, url: &'conn str, ) -> Result, ()>, Error> ``` ```rust pub async fn resource<'res>( &'res mut self, resource_url: &'res str, ) -> Result>, Error> ``` -------------------------------- ### HttpClient Initialization (Rust) Source: https://docs.rs/reqwless/0.14.0/src/reqwless/client.rs_search=std%3A%3Avec Initializes a new `HttpClient` instance. This struct is used to establish TCP connections and perform HTTP requests asynchronously. It requires references to a `TcpConnect` client and a `Dns` resolver. ```rust impl<'a, T, D> where T: TcpConnect + 'a, D: Dns + 'a, { /// Create a new HTTP client for a given connection handle and a target host. pub fn new(client: &'a T, dns: &'a D) -> Self { Self { client, dns, #[cfg(any(feature = "embedded-tls", feature = "esp-mbedtls"))] tls: None, } } /// Create a new HTTP client for a given connection handle and a target host. #[cfg(any(feature = "embedded-tls", feature = "esp-mbedtls"))] pub fn new_with_tls(client: &'a T, dns: &'a D, tls: TlsConfig<'a>) -> Self { Self { client, dns, ``` -------------------------------- ### HttpClient Creation Source: https://docs.rs/reqwless/0.14.0/reqwless/client/struct.HttpClient Provides methods for creating a new HttpClient instance, either with or without TLS configuration. ```APIDOC ## HttpClient Creation ### `new` Creates a new HTTP client for a given connection handle and a target host. #### Method `pub fn new(client: &'a T, dns: &'a D) -> Self` #### Parameters - **client** (`&'a T`): A reference to the TCP connection provider. - **dns** (`&'a D`): A reference to the DNS resolution provider. ### `new_with_tls` Creates a new HTTP client with TLS configuration for a given connection handle and a target host. #### Method `pub fn new_with_tls(client: &'a T, dns: &'a D, tls: TlsConfig<'a>) -> Self` #### Parameters - **client** (`&'a T`): A reference to the TCP connection provider. - **dns** (`&'a D`): A reference to the DNS resolution provider. - **tls** (`TlsConfig<'a>`): The TLS configuration to use. ``` -------------------------------- ### Test: Get Maximum Chunk Header Size Source: https://docs.rs/reqwless/0.14.0/src/reqwless/body_writer/buffering_chunked.rs_search= Unit tests for the `get_max_chunk_header_size` function. These tests check the calculation of the maximum header size for different buffer capacities, including edge cases where no header can fit. ```Rust #[test] fn can_get_max_chunk_header_size() { assert_eq!(0, get_max_chunk_header_size(0)); assert_eq!(0, get_max_chunk_header_size(1)); assert_eq!(0, get_max_chunk_header_size(2)); assert_eq!(0, get_max_chunk_header_size(3)); assert_eq!(3, get_max_chunk_header_size(0x00 + 2 + 2)); assert_eq!(3, get_max_chunk_header_size(0x01 + 2 + 2)); assert_eq!(3, get_max_chunk_header_size(0x0F + 2 + 2)); assert_eq!(4, get_max_chunk_header_size(0x10 + 2 + 2)); assert_eq!(4, get_max_chunk_header_size(0x11 + 2 + 2)); assert_eq!(4, get_max_chunk_header_size(0x12 + 2 + 2)); } ``` -------------------------------- ### BufRead Implementation for BodyReader Source: https://docs.rs/reqwless/0.14.0/reqwless/response/enum.BodyReader_search= Implements the BufRead trait for BodyReader, enabling buffered reading operations. This includes methods like `fill_buf` to get buffered data and `consume` to manage the buffer state. ```rust impl BufRead for BodyReader where B: BufRead + Read, { async fn fill_buf(&mut self) -> Result<&[u8], Self::Error> // ... implementation details ... fn consume(&mut self, amt: usize) // ... implementation details ... } ``` -------------------------------- ### Get Body Reader - Rust Source: https://docs.rs/reqwless/0.14.0/reqwless/response/struct.ResponseBody Provides a `BodyReader` for the `ResponseBody`. This method consumes the `ResponseBody` and returns a reader that can be used to access the response body content. The reader is a `BufferingReader` which wraps the underlying reader `C`. ```rust pub fn reader(self) -> BodyReader> ``` -------------------------------- ### Blanket Implementations Source: https://docs.rs/reqwless/0.14.0/reqwless/response/struct.HeaderIterator_search=std%3A%3Avec Provides documentation for blanket implementations, which apply traits to types under certain conditions. ```APIDOC ## Blanket Implementations ### Description Blanket implementations allow traits to be automatically implemented for a wide range of types based on specific bounds or other trait implementations. ### Key Implementations #### `impl Any for T` - **Description**: Implements the `Any` trait for any type `T` that is `'static` and not `?Sized`. This allows for dynamic type checking. - **Method**: `type_id(&self) -> TypeId` - Gets the `TypeId` of `self`. #### `impl Borrow for T` - **Description**: Implements `Borrow` for `T`, allowing immutable borrowing. - **Method**: `borrow(&self) -> &T` - Immutably borrows from an owned value. #### `impl BorrowMut for T` - **Description**: Implements `BorrowMut` for `T`, allowing mutable borrowing. - **Method**: `borrow_mut(&mut self) -> &mut T` - Mutably borrows from an owned value. #### `impl From for T` - **Description**: Implements `From` for `T`, a trivial conversion. - **Method**: `from(t: T) -> T` - Returns the argument unchanged. #### `impl Into for T where U: From` - **Description**: Implements `Into` for `T` when `U` implements `From`. - **Method**: `into(self) -> U` - Calls `U::from(self)`. #### `impl IntoIterator for I where I: Iterator` - **Description**: Implements `IntoIterator` for any type `I` that is already an `Iterator`. - **Associated Types**: `Item = ::Item`, `IntoIter = I` - **Method**: `into_iter(self) -> I` - Creates an iterator from a value. #### `impl Same for T` - **Description**: Implements the `Same` trait for any type `T`. - **Associated Type**: `Output = T` #### `impl TryFrom for T where U: Into` - **Description**: Implements `TryFrom` for `T` when `U` implements `Into`. - **Associated Type**: `Error = Infallible` - **Method**: `try_from(value: U) -> Result>::Error>` - Performs the conversion. #### `impl TryInto for T where U: TryFrom` - **Description**: Implements `TryInto` for `T` when `U` implements `TryFrom`. - **Associated Type**: `Error = >::Error` - **Method**: `try_into(self) -> Result>::Error>` - Performs the conversion. #### `impl VZip for T where V: MultiLane` - **Description**: Implements `VZip` for type `T` under the condition that `V` is a `MultiLane`. **Source**: [Link to source code, if available] ``` -------------------------------- ### HTTP Request Methods Source: https://docs.rs/reqwless/0.14.0/reqwless/request/enum.Method The reqwless library provides an enum `Method` to represent standard HTTP request methods. This enum includes variants for GET, PUT, POST, DELETE, HEAD, PATCH, OPTIONS, CONNECT, and TRACE. ```APIDOC ## Enum Method ### Description HTTP request methods. ### Variants * `GET` * `PUT` * `POST` * `DELETE` * `HEAD` * `PATCH` * `OPTIONS` * `CONNECT` * `TRACE` ### Method `reqwless::request` ### Implementations #### `impl Method` ##### `pub fn as_str(&self) -> &str` str representation of method. #### `impl Clone for Method` ##### `fn clone(&self) -> Method` Returns a duplicate of the value. ##### `fn clone_from(&mut self, source: &Self)` Performs copy-assignment from `source`. #### `impl Debug for Method` ##### `fn fmt(&self, f: &mut Formatter<'_>) -> Result` Formats the value using the given formatter. #### `impl PartialEq for Method` ##### `fn eq(&self, other: &Method) -> bool` Tests for `self` and `other` values to be equal, and is used by `==`. ##### `fn ne(&self, other: &Rhs) -> bool` Tests for `!=`. #### `impl Copy for Method` #### `impl StructuralPartialEq for Method` #### Auto Trait Implementations * `impl Freeze for Method` * `impl RefUnwindSafe for Method` * `impl Send for Method` * `impl Sync for Method` * `impl Unpin for Method` * `impl UnwindSafe for Method` #### 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 CloneToUninit for T` * `unsafe fn clone_to_uninit(&self, dest: *mut u8)` Performs copy-assignment from `self` to `dest`. * `impl From for T` * `fn from(t: T) -> T` Returns the argument unchanged. * `impl Into for T` * `fn into(self) -> U` Calls `U::from(self)`. * `impl Same for T` * `type Output = T` Should always be `Self`. * `impl TryFrom for T` * `type Error = Infallible` The type returned in the event of a conversion error. * `fn try_from(value: U) -> Result>::Error>` Performs the conversion. * `impl TryInto for T` * `type Error = >::Error` The type returned in the event of a conversion error. * `fn try_into(self) -> Result>::Error>` Performs the conversion. * `impl VZip for T` * `fn vzip(self) -> V` ``` -------------------------------- ### Test TLS 1.3 with specific ciphersuites using OpenSSL Source: https://docs.rs/reqwless/0.14.0/reqwless/index_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E This command tests if a server supports TLS 1.3 with a specific set of ciphersuites, without limiting signature algorithms. It's a fallback test if the previous command fails, indicating potential issues with signature algorithm negotiation. ```bash openssl s_client -tls1_3 -ciphersuites TLS_AES_128_GCM_SHA256 -connect hostname:443 ```