Skip to main content

Request

Struct Request 

Source
pub struct Request { /* private fields */ }
Expand description

An HTTP request, returns a Response.

Implementations§

Source§

impl Request

Source

pub fn new(method: Method, url: Url) -> Self

Create a new instance.

This method is particularly useful when input URLs might be passed by third parties, and you don’t want to panic if they’re malformed. If URLs are statically encoded, it might be easier to use one of the shorthand methods instead.

§Examples
fn main() -> crux_http::Result<()> {
use crux_http::{Url, Method};

let url = Url::parse("https://httpbin.org/get")?;
let req = crux_http::Request::new(Method::GET, url);
Source

pub fn query<T: DeserializeOwned>(&self) -> Result<T>

Get the URL querystring.

§Examples
fn main() -> crux_http::Result<()> {
use serde::{Deserialize, Serialize};
use crux_http::{Request, Method, Url};
#[derive(Serialize, Deserialize)]
struct Index {
    page: u32
}

let req = Request::new(Method::GET, Url::parse("https://httpbin.org/get?page=2")?);
let Index { page } = req.query()?;
assert_eq!(page, 2);
§Errors

Returns an error if the query string could not be deserialized.

Source

pub fn set_query(&mut self, query: &impl Serialize) -> Result<()>

Set the URL querystring.

§Examples
fn main() -> crux_http::Result<()> {
#[derive(Serialize, Deserialize)]
struct Index {
    page: u32
}

let query = Index { page: 2 };
let mut req = Request::new(Method::GET, Url::parse("https://httpbin.org/get")?);
req.set_query(&query)?;
assert_eq!(req.url().query(), Some("page=2"));
assert_eq!(req.url().as_str(), "https://httpbin.org/get?page=2");
§Errors

Returns an error if the query string could not be serialized.

Source

pub fn header(&self, name: impl AsHeaderName) -> Option<&HeaderValue>

Get an HTTP header.

§Examples
fn main() -> crux_http::Result<()> {
let mut req = Request::new(Method::GET, Url::parse("https://httpbin.org/get")?);
req.insert_header("X-Requested-With", HeaderValue::from_static("surf"));
assert_eq!(req.header("X-Requested-With").unwrap(), "surf");
Source

pub fn header_mut( &mut self, name: impl AsHeaderName, ) -> Option<&mut HeaderValue>

Get a mutable reference to a header.

Source

pub fn header_all(&self, name: impl AsHeaderName) -> GetAll<'_, HeaderValue>

Get all values for a header name.

Source

pub fn insert_header( &mut self, name: impl IntoHeaderName, value: HeaderValue, ) -> Option<HeaderValue>

Set an HTTP header, replacing any existing value.

Returns the previous value for that header name, if any.

Source

pub fn append_header( &mut self, name: impl IntoHeaderName, value: HeaderValue, ) -> bool

Append a header to the headers.

Unlike insert_header 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.

Returns true if the value was appended to an existing entry, false if it was the first value for that name.

Source

pub fn remove_header(&mut self, name: impl AsHeaderName) -> Option<HeaderValue>

Remove a header.

Source

pub fn iter(&self) -> Iter<'_, HeaderValue>

An iterator visiting all header pairs in arbitrary order.

Source

pub fn iter_mut(&mut self) -> IterMut<'_, HeaderValue>

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

Source

pub fn header_names(&self) -> Keys<'_, HeaderValue>

An iterator visiting all header names in arbitrary order.

Source

pub fn header_values(&self) -> Values<'_, HeaderValue>

An iterator visiting all header values in arbitrary order.

Source

pub fn set_header(&mut self, key: impl IntoHeaderName, value: impl AsRef<str>)

👎Deprecated since 0.16.0:

Use insert_header instead

Set an HTTP header.

§Examples
fn main() -> crux_http::Result<()> {
let mut req = Request::new(Method::GET, Url::parse("https://httpbin.org/get")?);
req.insert_header("X-Requested-With", HeaderValue::from_static("surf"));
assert_eq!(req.header("X-Requested-With").unwrap(), "surf");
Source

pub fn method(&self) -> &Method

Get the request HTTP method.

§Examples
fn main() -> crux_http::Result<()> {
let req = Request::new(Method::GET, Url::parse("https://httpbin.org/get")?);
assert_eq!(req.method(), &Method::GET);
Source

pub fn url(&self) -> &Url

Get the request url.

§Examples
fn main() -> crux_http::Result<()> {
let req = Request::new(Method::GET, Url::parse("https://httpbin.org/get")?);
assert_eq!(req.url(), &Url::parse("https://httpbin.org/get")?);
Source

pub fn url_mut(&mut self) -> &mut Url

Get a mutable reference to the request url.

This is useful for middleware that needs to rewrite the request URL.

Source

pub fn content_type(&self) -> Option<Mime>

Get the request content type as a Mime.

Gets the Content-Type header and parses it to a Mime type.

Read more on MDN

§Panics

This method will panic if an invalid MIME type was set as a header. Use the set_header method to bypass any checks.

Source

pub fn set_content_type(&mut self, mime: &Mime)

Set the request content type from a Mime.

Read more on MDN

Source

pub fn len(&self) -> Option<usize>

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.

Source

pub fn is_empty(&self) -> Option<bool>

Returns true if the set length of the body stream is zero, false otherwise.

Source

pub fn set_body(&mut self, body: impl Into<Body>)

Pass an AsyncRead stream as the request body.

§Mime

The encoding is set to application/octet-stream.

Source

pub fn take_body(&mut self) -> Body

Take the request body as a Body.

This method can be called after the body has already been taken or read, but will return an empty Body.

This is useful for consuming the body via an AsyncReader or AsyncBufReader.

Source

pub fn body_json(&mut self, json: &impl Serialize) -> Result<()>

Pass JSON as the request body.

§Mime

The content-type is set to application/json.

§Errors

This method will return an error if the provided data could not be serialized to JSON.

Source

pub fn body_string(&mut self, string: String)

Pass a string as the request body.

§Mime

The content-type is set to text/plain; charset=utf-8.

Source

pub fn body_bytes(&mut self, bytes: impl AsRef<[u8]>)

Pass bytes as the request body.

§Mime

The content-type is set to application/octet-stream.

Source

pub fn body_form(&mut self, form: &impl Serialize) -> Result<()>

Pass a form as the request body.

§Mime

The content-type is set to application/x-www-form-urlencoded.

§Errors

An error will be returned if the encoding failed.

Source

pub fn middleware(&mut self, middleware: impl Middleware)

Push middleware onto a per-request middleware stack.

Important: Setting per-request middleware incurs extra allocations. Creating a Client with middleware is recommended.

Client middleware is run before per-request middleware.

See the middleware submodule for more information on middleware.

§Examples
fn main() -> crux_http::Result<()> {
let mut req = Request::new(Method::GET, Url::parse("https://httpbin.org/get")?);
req.middleware(crux_http::middleware::Redirect::default());

Trait Implementations§

Source§

impl AsMut<HeaderMap> for Request

Source§

fn as_mut(&mut self) -> &mut HeaderMap

Converts this type into a mutable reference of the (usually inferred) input type.
Source§

impl AsRef<HeaderMap> for Request

Source§

fn as_ref(&self) -> &HeaderMap

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl Clone for Request

Source§

fn clone(&self) -> Request

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Request

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl From<Request<Body>> for Request

Source§

fn from(req: Request<Body>) -> Self

Converts to this type from the input type.
Source§

impl From<Request> for Request<Body>

Source§

fn from(req: Request) -> Self

Converts to this type from the input type.
Source§

impl Index<&str> for Request

Source§

fn index(&self, name: &str) -> &HeaderValue

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

§Panics

Panics if the name is not present in Request.

Source§

type Output = HeaderValue

The returned type after indexing.
Source§

impl<'a> IntoIterator for &'a Request

Source§

type Item = (&'a HeaderName, &'a HeaderValue)

The type of the elements being iterated over.
Source§

type IntoIter = Iter<'a, HeaderValue>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<'a> IntoIterator for &'a mut Request

Source§

type Item = (&'a HeaderName, &'a mut HeaderValue)

The type of the elements being iterated over.
Source§

type IntoIter = IterMut<'a, HeaderValue>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

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

fn clone_into(&self, target: &mut T)

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

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.