Struct Request

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

An HTTP request.

The Request gives endpoints access to basic information about the incoming request, route parameters, and various ways of accessing the request’s body.

Requests also provide extensions, a type map primarily used for low-level communication between middleware and endpoints.

Implementations§

Source§

impl<State> Request<State>

Source

pub fn method(&self) -> Method

Access the request’s HTTP method.

§Examples
use tide::Request;

let mut app = tide::new();
app.at("/").get(|req: Request<()>| async move {
    assert_eq!(req.method(), http_types::Method::Get);
    Ok("")
});
app.listen("127.0.0.1:8080").await?;
Source

pub fn url(&self) -> &Url

Access the request’s full URI method.

§Examples
use tide::Request;

let mut app = tide::new();
app.at("/").get(|req: Request<()>| async move {
    assert_eq!(req.url(), &"/".parse::<tide::http::Url>().unwrap());
    Ok("")
});
app.listen("127.0.0.1:8080").await?;
Source

pub fn version(&self) -> Option<Version>

Access the request’s HTTP version.

§Examples
use tide::Request;

let mut app = tide::new();
app.at("/").get(|req: Request<()>| async move {
    assert_eq!(req.version(), Some(http_types::Version::Http1_1));
    Ok("")
});
app.listen("127.0.0.1:8080").await?;
Source

pub fn peer_addr(&self) -> Option<&str>

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

Source

pub fn local_addr(&self) -> Option<&str>

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

Source

pub fn remote(&self) -> Option<&str>

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
Source

pub fn host(&self) -> Option<&str>

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
Source

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

Get the request content type as a Mime.

This gets the request Content-Type header.

Read more on MDN

Source

pub fn header(&self, key: impl Into<HeaderName>) -> Option<&HeaderValues>

Get an HTTP header.

§Examples
use tide::Request;

let mut app = tide::new();
app.at("/").get(|req: Request<()>| async move {
    assert_eq!(req.header("X-Forwarded-For").unwrap(), "127.0.0.1");
    Ok("")
});
app.listen("127.0.0.1:8080").await?;
Source

pub fn header_mut( &mut self, name: impl Into<HeaderName>, ) -> Option<&mut HeaderValues>

Get a mutable reference to a header.

Source

pub fn insert_header( &mut self, name: impl Into<HeaderName>, values: impl ToHeaderValues, ) -> Option<HeaderValues>

Set an HTTP header.

Source

pub fn append_header( &mut self, name: impl Into<HeaderName>, values: impl ToHeaderValues, )

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.

Source

pub fn remove_header( &mut self, name: impl Into<HeaderName>, ) -> Option<HeaderValues>

Remove a header.

Source

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

An iterator visiting all header pairs in arbitrary order.

Source

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

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

Source

pub fn header_names(&self) -> Names<'_>

An iterator visiting all header names in arbitrary order.

Source

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

An iterator visiting all header values in arbitrary order.

Source

pub fn ext<T: Send + Sync + 'static>(&self) -> Option<&T>

Get a request extension value.

Source

pub fn ext_mut<T: Send + Sync + 'static>(&mut self) -> Option<&mut T>

Get a mutable reference to value stored in request extensions.

Source

pub fn set_ext<T: Send + Sync + 'static>(&mut self, val: T) -> Option<T>

Set a request extension value.

Source

pub fn state(&self) -> &State

Access application scoped state.

Source

pub fn param(&self, key: &str) -> Result<&str>

Extract and parse a route parameter by name.

Returns the parameter as a &str, borrowed from this Request.

The name should not include the leading : or the trailing * (if any).

§Errors

An error is returned if key is not a valid parameter for the route.

§Examples
use tide::{Request, Result};

async fn greet(req: Request<()>) -> Result<String> {
    let name = req.param("name").unwrap_or("world");
    Ok(format!("Hello, {}!", name))
}

let mut app = tide::new();
app.at("/hello").get(greet);
app.at("/hello/:name").get(greet);
app.listen("127.0.0.1:8080").await?;
Source

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

Parse the URL query component into a struct, using serde_qs. To get the entire query as an unparsed string, use request.url().query()

use tide::prelude::*;
let mut app = tide::new();

#[derive(Deserialize)]
#[serde(default)]
struct Page {
    size: u8,
    offset: u8,
}
impl Default for Page {
    fn default() -> Self {
        Self {
            size: 25,
            offset: 0,
        }
    }
}
app.at("/pages").post(|req: tide::Request<()>| async move {
    let page: Page = req.query()?;
    Ok(format!("page {}, with {} items", page.offset, page.size))
});

app.listen("localhost:8000").await?;

// $ curl localhost:8000/pages
// page 0, with 25 items

// $ curl localhost:8000/pages?offset=1
// page 1, with 25 items

// $ curl localhost:8000/pages?offset=2&size=50
// page 2, with 50 items

// $ curl localhost:8000/pages?size=5000
// failed with reason: number too large to fit in target type

// $ curl localhost:8000/pages?size=all
// failed with reason: invalid digit found in string
Source

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

Set the body reader.

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 async fn body_bytes(&mut self) -> Result<Vec<u8>>

Reads the entire request body into a byte buffer.

This method can be called after the body has already been read, but will produce an empty buffer.

§Errors

Any I/O error encountered while reading the body is immediately returned as an Err.

§Examples
use tide::Request;

let mut app = tide::new();
app.at("/").get(|mut req: Request<()>| async move {
    let _body: Vec<u8> = req.body_bytes().await.unwrap();
    Ok("")
});
app.listen("127.0.0.1:8080").await?;
Source

pub async fn body_string(&mut self) -> Result<String>

Reads the entire request body into a string.

This method can be called after the body has already been read, but will produce an empty buffer.

§Errors

Any I/O error encountered while reading the body is immediately returned as an Err.

If the body cannot be interpreted as valid UTF-8, an Err is returned.

§Examples
use tide::Request;

let mut app = tide::new();
app.at("/").get(|mut req: Request<()>| async move {
    let _body: String = req.body_string().await.unwrap();
    Ok("")
});
app.listen("127.0.0.1:8080").await?;
Source

pub async fn body_json<T: DeserializeOwned>(&mut self) -> Result<T>

Reads and deserialized the entire request body via json.

§Errors

Any I/O error encountered while reading the body is immediately returned as an Err.

If the body cannot be interpreted as valid json for the target type T, an Err is returned.

Source

pub async fn body_form<T: DeserializeOwned>(&mut self) -> Result<T>

Parse the request body as a form.

use tide::prelude::*;
let mut app = tide::new();

#[derive(Deserialize)]
struct Animal {
  name: String,
  legs: u8
}

app.at("/").post(|mut req: tide::Request<()>| async move {
    let animal: Animal = req.body_form().await?;
    Ok(format!(
        "hello, {}! i've put in an order for {} shoes",
        animal.name, animal.legs
    ))
});

app.listen("localhost:8000").await?;

// $ curl localhost:8000/orders/shoes -d "name=chashu&legs=4"
// hello, chashu! i've put in an order for 4 shoes

// $ curl localhost:8000/orders/shoes -d "name=mary%20millipede&legs=750"
// number too large to fit in target type
Source

pub fn cookie(&self, name: &str) -> Option<Cookie<'static>>

returns a Cookie by name of the cookie.

Source

pub fn session(&self) -> &Session

Retrieves a reference to the current session.

§Panics

This method will panic if a tide::sessions:SessionMiddleware has not been run.

Source

pub fn session_mut(&mut self) -> &mut Session

Retrieves a mutable reference to the current session.

§Panics

This method will panic if a tide::sessions:SessionMiddleware has not been run.

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 request has a set body stream length of zero, false otherwise.

Trait Implementations§

Source§

impl<State> AsMut<Headers> for Request<State>

Source§

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

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

impl<State> AsMut<Request> for Request<State>

Source§

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

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

impl<State> AsRef<Headers> for Request<State>

Source§

fn as_ref(&self) -> &Headers

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

impl<State> AsRef<Request> for Request<State>

Source§

fn as_ref(&self) -> &Request

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

impl<State> AsyncRead for Request<State>

Source§

fn poll_read( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8], ) -> Poll<Result<usize>>

Attempt to read from the AsyncRead into buf. Read more
Source§

fn poll_read_vectored( self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &mut [IoSliceMut<'_>], ) -> Poll<Result<usize, Error>>

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

impl<State: Debug> Debug for Request<State>

Source§

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

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

impl<State> Index<&str> for Request<State>

Source§

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

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

§Panics

Panics if the name is not present in Request.

Source§

type Output = HeaderValues

The returned type after indexing.
Source§

impl<State> Index<HeaderName> for Request<State>

Source§

fn index(&self, name: HeaderName) -> &HeaderValues

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

§Panics

Panics if the name is not present in Request.

Source§

type Output = HeaderValues

The returned type after indexing.
Source§

impl<State: Default> Into<Request<State>> for Request

Source§

fn into(self) -> Request<State>

Converts this type into the (usually inferred) input type.
Source§

impl<State> Into<Request> for Request<State>

Source§

fn into(self) -> Request

Converts this type into the (usually inferred) input type.
Source§

impl<State: Clone + Send + Sync + 'static> Into<Response> for Request<State>

Source§

fn into(self) -> Response

Converts this type into the (usually inferred) input type.
Source§

impl<'a, State> IntoIterator for &'a Request<State>

Source§

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

The type of the elements being iterated over.
Source§

type IntoIter = Iter<'a>

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, State> IntoIterator for &'a mut Request<State>

Source§

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

The type of the elements being iterated over.
Source§

type IntoIter = IterMut<'a>

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<State> IntoIterator for Request<State>

Source§

fn into_iter(self) -> Self::IntoIter

Returns a iterator of references over the remaining items.

Source§

type Item = (HeaderName, HeaderValues)

The type of the elements being iterated over.
Source§

type IntoIter = IntoIter

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

impl<'__pin, State> Unpin for Request<State>
where PinnedFieldsOf<__Origin<'__pin, State>>: Unpin,

Auto Trait Implementations§

§

impl<State> Freeze for Request<State>
where State: Freeze,

§

impl<State> !RefUnwindSafe for Request<State>

§

impl<State> Send for Request<State>
where State: Send,

§

impl<State> Sync for Request<State>
where State: Sync,

§

impl<State> !UnwindSafe for Request<State>

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<R> AsyncReadExt for R
where R: AsyncRead + ?Sized,

Source§

fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> ReadFuture<'a, Self>
where Self: Unpin,

Reads some bytes from the byte stream. Read more
Source§

fn read_vectored<'a>( &'a mut self, bufs: &'a mut [IoSliceMut<'a>], ) -> ReadVectoredFuture<'a, Self>
where Self: Unpin,

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

fn read_to_end<'a>( &'a mut self, buf: &'a mut Vec<u8>, ) -> ReadToEndFuture<'a, Self>
where Self: Unpin,

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

fn read_to_string<'a>( &'a mut self, buf: &'a mut String, ) -> ReadToStringFuture<'a, Self>
where Self: Unpin,

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

fn read_exact<'a>(&'a mut self, buf: &'a mut [u8]) -> ReadExactFuture<'a, Self>
where Self: Unpin,

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

fn take(self, limit: u64) -> Take<Self>
where Self: Sized,

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

fn bytes(self) -> Bytes<Self>
where Self: Sized,

Converts this AsyncRead into a Stream of bytes. Read more
Source§

fn chain<R>(self, next: R) -> Chain<Self, R>
where R: AsyncRead, Self: Sized,

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

fn boxed_reader<'a>(self) -> Pin<Box<dyn AsyncRead + Send + 'a>>
where Self: Sized + Send + 'a,

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

impl<R> AsyncReadExt for R
where R: AsyncRead + ?Sized,

Source§

fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> ReadFuture<'a, Self>
where Self: Unpin,

Reads some bytes from the byte stream. Read more
Source§

fn read_vectored<'a>( &'a mut self, bufs: &'a mut [IoSliceMut<'a>], ) -> ReadVectoredFuture<'a, Self>
where Self: Unpin,

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

fn read_to_end<'a>( &'a mut self, buf: &'a mut Vec<u8>, ) -> ReadToEndFuture<'a, Self>
where Self: Unpin,

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

fn read_to_string<'a>( &'a mut self, buf: &'a mut String, ) -> ReadToStringFuture<'a, Self>
where Self: Unpin,

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

fn read_exact<'a>(&'a mut self, buf: &'a mut [u8]) -> ReadExactFuture<'a, Self>
where Self: Unpin,

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

fn take(self, limit: u64) -> Take<Self>
where Self: Sized,

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

fn bytes(self) -> Bytes<Self>
where Self: Sized,

Converts this AsyncRead into a Stream of bytes. Read more
Source§

fn chain<R>(self, next: R) -> Chain<Self, R>
where R: AsyncRead, Self: Sized,

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

fn boxed_reader<'a>(self) -> Pin<Box<dyn AsyncRead + Send + 'a>>
where Self: Sized + Send + 'a,

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

impl<R> AsyncReadExt for R
where R: AsyncRead + ?Sized,

Source§

fn chain<R>(self, next: R) -> Chain<Self, R>
where Self: Sized, R: AsyncRead,

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

fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> Read<'a, Self>
where Self: Unpin,

Tries to read some bytes directly into the given buf in asynchronous manner, returning a future type. Read more
Source§

fn read_vectored<'a>( &'a mut self, bufs: &'a mut [IoSliceMut<'a>], ) -> ReadVectored<'a, Self>
where Self: Unpin,

Creates a future which will read from the AsyncRead into bufs using vectored IO operations. Read more
Source§

fn read_exact<'a>(&'a mut self, buf: &'a mut [u8]) -> ReadExact<'a, Self>
where Self: Unpin,

Creates a future which will read exactly enough bytes to fill buf, returning an error if end of file (EOF) is hit sooner. Read more
Source§

fn read_to_end<'a>(&'a mut self, buf: &'a mut Vec<u8>) -> ReadToEnd<'a, Self>
where Self: Unpin,

Creates a future which will read all the bytes from this AsyncRead. Read more
Source§

fn read_to_string<'a>( &'a mut self, buf: &'a mut String, ) -> ReadToString<'a, Self>
where Self: Unpin,

Creates a future which will read all the bytes from this AsyncRead. Read more
Source§

fn split(self) -> (ReadHalf<Self>, WriteHalf<Self>)
where Self: Sized + AsyncWrite,

Helper method for splitting this read/write object into two halves. Read more
Source§

fn take(self, limit: u64) -> Take<Self>
where Self: Sized,

Creates an AsyncRead adapter which will read at most limit bytes from the underlying reader. 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> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> ReadExt for T
where T: AsyncRead + ?Sized,

Source§

fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> ReadFuture<'a, Self>
where Self: Unpin,

Reads some bytes from the byte stream. Read more
Source§

fn read_vectored<'a>( &'a mut self, bufs: &'a mut [IoSliceMut<'a>], ) -> ReadVectoredFuture<'a, Self>
where Self: Unpin,

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

fn read_to_end<'a>( &'a mut self, buf: &'a mut Vec<u8>, ) -> ReadToEndFuture<'a, Self>
where Self: Unpin,

Reads all bytes from the byte stream. Read more
Source§

fn read_to_string<'a>( &'a mut self, buf: &'a mut String, ) -> ReadToStringFuture<'a, Self>
where Self: Unpin,

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

fn read_exact<'a>(&'a mut self, buf: &'a mut [u8]) -> ReadExactFuture<'a, Self>
where Self: Unpin,

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

fn take(self, limit: u64) -> Take<Self>
where Self: Sized,

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

fn by_ref(&mut self) -> &mut Self
where Self: Sized,

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

fn bytes(self) -> Bytes<Self>
where Self: Sized,

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

fn chain<R>(self, next: R) -> Chain<Self, R>
where R: AsyncRead, Self: Sized,

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

impl<T> Same for T

Source§

type Output = T

Should always be Self
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.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,