Struct tide::Request[][src]

pub struct Request<State> { /* fields omitted */ }
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

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?;

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?;

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?;

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 request content type as a Mime.

This gets the request Content-Type header.

Read more on MDN

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?;

Get a mutable reference to a header.

Set an HTTP header.

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.

Remove a header.

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.

Get a request extension value.

Get a mutable reference to value stored in request extensions.

Set a request extension value.

Access application scoped state.

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 :.

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?;

Fetch the wildcard from the route, if it exists

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

Examples
use tide::{Request, Result};

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

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

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

Examples
use std::collections::HashMap;
use tide::http::{self, convert::Deserialize};
use tide::Request;

// An owned structure:

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

let req: Request<()> = http::Request::get("https://httpbin.org/get?page=2&selections[width]=narrow&selections[height]=tall").into();
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 req: Request<()> = http::Request::get("https://httpbin.org/get?format=bananna").into();
let Query { format } = req.query().unwrap();
assert_eq!(format, "bananna");

Set the body reader.

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.

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?;

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?;

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.

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

returns a Cookie by name of the cookie.

Retrieves a reference to the current session.

Panics

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

Retrieves a mutable reference to the current session.

Panics

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

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.

Trait Implementations

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Attempt to read from the AsyncRead into buf. Read more

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

Formats the value using the given formatter. Read more

Performs the conversion.

Performs the conversion.

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

Reads some bytes from the byte stream. Read more

Like [read()][AsyncReadExt::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

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

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

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

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

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

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

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

Creates an AsyncRead adapter which will read at most limit bytes from the underlying reader. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. 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 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.