Struct http_types::Request[][src]

pub struct Request { /* fields omitted */ }
Expand description

An HTTP request.

Examples

use http_types::Request;

let mut req = Request::get("https://example.com");
req.set_body("Hello, Nori!");

Implementations

Create a new request.

Sets a string representation of the peer address of this request. This might take the form of an ip/fqdn and port or a local socket address.

Sets a string representation of the local address that this request was received on. This might take the form of an ip/fqdn and port, or a local socket address.

Get the peer socket address for the underlying transport, if that information is available for this request.

Get the local socket address for the underlying transport, if that information is available for this request.

Get the remote address for this request.

This is determined in the following priority:

  1. Forwarded header for key
  2. The first X-Forwarded-For header
  3. Peer address of the transport

Get the destination host for this request.

This is determined in the following priority:

  1. Forwarded header host key
  2. The first X-Forwarded-Host header
  3. Host header
  4. URL domain, if any

Get the HTTP method

Set the HTTP method.

Get a reference to the url.

Examples

use http_types::{Request, Response, StatusCode};
let mut req = Request::get("https://example.com");
assert_eq!(req.url().scheme(), "https");

Get a mutable reference to the url.

Examples

use http_types::{Method, Request, Response, StatusCode, Url};
let mut req = Request::get("https://example.com");
req.url_mut().set_scheme("http");
assert_eq!(req.url().scheme(), "http");

Set the request body.

Examples

use http_types::{Method, Request};

let mut req = Request::get("https://example.com");
req.set_body("Hello, Nori!");

Swaps the value of the body with another body, without deinitializing either one.

Examples

use http_types::{Body, Method, Request};

let mut req = Request::get("https://example.com");
req.set_body("Hello, Nori!");
let mut body: Body = req.replace_body("Hello, Chashu!");

let mut string = String::new();
body.read_to_string(&mut string).await?;
assert_eq!(&string, "Hello, Nori!");

Replace the request body with a new body, and return the old body.

Examples

use http_types::{Body, Request};

let mut req = Request::get("https://example.com");
req.set_body("Hello, Nori!");
let mut body = "Hello, Chashu!".into();
req.swap_body(&mut body);

let mut string = String::new();
body.read_to_string(&mut string).await?;
assert_eq!(&string, "Hello, Nori!");

Take the request body, replacing it with an empty body.

Examples

use http_types::{Body, Request};

let mut req = Request::get("https://example.com");
req.set_body("Hello, Nori!");
let mut body: Body = req.take_body();

let mut string = String::new();
body.read_to_string(&mut string).await?;
assert_eq!(&string, "Hello, Nori!");

Read the body as a string.

This consumes the request. If you want to read the body without consuming the request, consider using the take_body method and then calling Body::into_string or using the Request’s AsyncRead implementation to read the body.

Examples

use async_std::io::Cursor;
use http_types::{Body, Request};

let mut req = Request::get("https://example.com");

let cursor = Cursor::new("Hello Nori");
let body = Body::from_reader(cursor, None);
req.set_body(body);
assert_eq!(&req.body_string().await.unwrap(), "Hello Nori");

Read the body as bytes.

This consumes the Request. If you want to read the body without consuming the request, consider using the take_body method and then calling Body::into_bytes or using the Request’s AsyncRead implementation to read the body.

Examples

use http_types::{Body, Request};

let bytes = vec![1, 2, 3];
let mut req = Request::get("https://example.com");
req.set_body(Body::from_bytes(bytes));

let bytes = req.body_bytes().await?;
assert_eq!(bytes, vec![1, 2, 3]);

Read the body as JSON.

This consumes the request. If you want to read the body without consuming the request, consider using the take_body method and then calling Body::into_json or using the Request’s AsyncRead implementation to read the body.

Examples

use http_types::convert::{Deserialize, Serialize};
use http_types::{Body, Request};

#[derive(Debug, Serialize, Deserialize)]
struct Cat {
    name: String,
}

let cat = Cat {
    name: String::from("chashu"),
};
let mut req = Request::get("https://example.com");
req.set_body(Body::from_json(&cat)?);

let cat: Cat = req.body_json().await?;
assert_eq!(&cat.name, "chashu");

Read the body as x-www-form-urlencoded.

This consumes the request. If you want to read the body without consuming the request, consider using the take_body method and then calling Body::into_json or using the Request’s AsyncRead implementation to read the body.

Examples

use http_types::convert::{Deserialize, Serialize};
use http_types::{Body, Request};

#[derive(Debug, Serialize, Deserialize)]
struct Cat {
    name: String,
}

let cat = Cat {
    name: String::from("chashu"),
};
let mut req = Request::get("https://example.com");
req.set_body(Body::from_form(&cat)?);

let cat: Cat = req.body_form().await?;
assert_eq!(&cat.name, "chashu");

Get an HTTP header.

Get a mutable reference to a header.

Remove a header.

Set an HTTP header.

Examples

use http_types::Request;

let mut req = Request::get("https://example.com");
req.insert_header("Content-Type", "text/plain");

Append a header to the headers.

Unlike insert this function will not override the contents of a header, but insert a header if there aren’t any. Or else append to the existing list of headers.

Examples

use http_types::Request;

let mut req = Request::get("https://example.com");
req.append_header("Content-Type", "text/plain");

Set the response MIME.

Get the current content type

Get the length of the body stream, if it has been set.

This value is set when passing a fixed-size object into as the body. E.g. a string, or a buffer. Consumers of this API should check this value to decide whether to use Chunked encoding, or set the response length.

Returns true if the request has a set body stream length of zero, false otherwise.

Get the HTTP version, if one has been set.

Examples

use http_types::{Request, Version};

let mut req = Request::get("https://example.com");
assert_eq!(req.version(), None);

req.set_version(Some(Version::Http2_0));
assert_eq!(req.version(), Some(Version::Http2_0));

Set the HTTP version.

Examples

use http_types::{Request, Version};

let mut req = Request::get("https://example.com");
req.set_version(Some(Version::Http2_0));

Sends trailers to the a receiver.

Receive trailers from a sender.

Returns true if sending trailers is in progress.

An iterator visiting all header pairs in arbitrary order.

An iterator visiting all header pairs in arbitrary order, with mutable references to the values.

An iterator visiting all header names in arbitrary order.

An iterator visiting all header values in arbitrary order.

Returns a reference to the existing local state.

Returns a mutuable reference to the existing local state.

Examples

use http_types::{Request, Version};

let mut req = Request::get("https://example.com");
req.ext_mut().insert("hello from the extension");
assert_eq!(req.ext().get(), Some(&"hello from the extension"));

Get the URL querystring.

Examples

use http_types::convert::Deserialize;
use http_types::Request;
use std::collections::HashMap;

// An owned structure:

#[derive(Deserialize)]
struct Index {
    page: u32,
    selections: HashMap<String, String>,
}

let mut req = Request::get("https://httpbin.org/get?page=2&selections[width]=narrow&selections[height]=tall");
let Index { page, selections } = req.query().unwrap();
assert_eq!(page, 2);
assert_eq!(selections["width"], "narrow");
assert_eq!(selections["height"], "tall");

// Using borrows:

#[derive(Deserialize)]
struct Query<'q> {
    format: &'q str,
}

let mut req = Request::get("https://httpbin.org/get?format=bananna");
let Query { format } = req.query().unwrap();
assert_eq!(format, "bananna");

Set the URL querystring.

Examples

use http_types::convert::Serialize;
use http_types::{Method, Request};
use std::collections::HashMap;

#[derive(Serialize)]
struct Index {
    page: u32,
    topics: Vec<&'static str>,
}

let query = Index { page: 2, topics: vec!["rust", "crabs", "crustaceans"] };
let mut req = Request::get("https://httpbin.org/get");
req.set_query(&query).unwrap();
assert_eq!(req.url().query(), Some("page=2&topics[0]=rust&topics[1]=crabs&topics[2]=crustaceans"));

Create a GET request.

The GET method requests a representation of the specified resource. Requests using GET should only retrieve data.

Examples

use http_types::{Method, Request};

let mut req = Request::get("https://example.com");
req.set_body("Hello, Nori!");
assert_eq!(req.method(), Method::Get);

Create a HEAD request.

The HEAD method asks for a response identical to that of a GET request, but without the response body.

Examples

use http_types::{Method, Request};

let mut req = Request::head("https://example.com");
assert_eq!(req.method(), Method::Head);

Create a POST request.

The POST method is used to submit an entity to the specified resource, often causing a change in state or side effects on the server.

Examples

use http_types::{Method, Request};

let mut req = Request::post("https://example.com");
assert_eq!(req.method(), Method::Post);

Create a PUT request.

The PUT method replaces all current representations of the target resource with the request payload.

Examples

use http_types::{Method, Request};

let mut req = Request::put("https://example.com");
assert_eq!(req.method(), Method::Put);

Create a DELETE request.

The DELETE method deletes the specified resource.

Examples

use http_types::{Method, Request};

let mut req = Request::delete("https://example.com");
assert_eq!(req.method(), Method::Delete);

Create a CONNECT request.

The CONNECT method establishes a tunnel to the server identified by the target resource.

Examples

use http_types::{Method, Request};

let mut req = Request::connect("https://example.com");
assert_eq!(req.method(), Method::Connect);

Create a OPTIONS request.

The OPTIONS method is used to describe the communication options for the target resource.

Examples

use http_types::{Method, Request};

let mut req = Request::options("https://example.com");
assert_eq!(req.method(), Method::Options);

Create a TRACE request.

The TRACE method performs a message loop-back test along the path to the target resource.

Examples

use http_types::{Method, Request};

let mut req = Request::trace("https://example.com");
assert_eq!(req.method(), Method::Trace);

Create a PATCH request.

The PATCH method is used to apply partial modifications to a resource.

Examples

use http_types::{Method, Request};

let mut req = Request::patch("https://example.com");
assert_eq!(req.method(), Method::Patch);

Trait Implementations

Performs the conversion.

Performs the conversion.

Attempt to return the contents of the internal buffer, filling it with more data from the inner reader if it is empty. Read more

Tells this buffer that amt bytes have been consumed from the buffer, so they should no longer be returned in calls to poll_read. Read more

Attempt to read from the AsyncRead into buf. Read more

Attempt to read from the AsyncRead into bufs using vectored IO operations. Read more

Clone the request, resolving the body to Body::empty() and removing extensions.

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

Performs the conversion.

Returns a reference to the value corresponding to the supplied name.

Panics

Panics if the name is not present in Request.

The returned type after indexing.

Returns a reference to the value corresponding to the supplied name.

Panics

Panics if the name is not present in Request.

The returned type after indexing.

Returns a iterator of references over the remaining items.

The type of the elements being iterated over.

Which kind of iterator are we turning this into?

The type of the elements being iterated over.

Which kind of iterator are we turning this into?

Creates an iterator from a value. Read more

The type of the elements being iterated over.

Which kind of iterator are we turning this into?

Creates an iterator from a value. Read more

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Returns the contents of the internal buffer, filling it with more data if empty. Read more

Consumes amt buffered bytes. Read more

Reads all bytes and appends them into buf until the delimiter byte or EOF is found. Read more

Reads all bytes and appends them into buf until a newline (the 0xA byte) or EOF is found. Read more

Returns a stream over the lines of this byte stream. Read more

Returns a stream over the contents of this reader split on the specified byte. Read more

Reads some bytes from the byte stream. Read more

Like read(), except it reads into a slice of buffers. Read more

Reads the entire contents and appends them to a Vec. Read more

Reads the entire contents and appends them to a String. Read more

Reads the exact number of bytes required to fill buf. Read more

Creates an adapter which will read at most limit bytes from it. Read more

Converts this [AsyncRead] into a [Stream] of bytes. Read more

Creates an adapter which will chain this stream with another. Read more

Boxes the reader and changes its type to dyn AsyncRead + Send + 'a. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Reads all bytes into buf until the delimiter byte or EOF is reached. Read more

Reads all bytes and appends them into buf until a newline (the 0xA byte) is reached. Read more

Returns a stream over the lines of this byte stream. Read more

Returns a stream over the contents of this reader split on the byte byte. Read more

Performs the conversion.

Performs the conversion.

Reads some bytes from the byte stream. Read more

Like read, except that it reads into a slice of buffers. Read more

Reads all bytes from the byte stream. Read more

Reads all bytes from the byte stream and appends them into a string. Read more

Reads the exact number of bytes required to fill buf. Read more

Creates an adaptor which will read at most limit bytes from it. Read more

Creates a “by reference” adaptor for this instance of Read. Read more

Transforms this Read instance to a Stream over its bytes. Read more

Creates an adaptor which will chain this stream with another. Read more

Should always be Self

The resulting type after obtaining ownership.

Creates owned data from borrowed data, usually by cloning. Read more

🔬 This is a nightly-only experimental API. (toowned_clone_into)

recently added

Uses borrowed data to replace owned data, usually by cloning. Read more

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.