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:
Forwarded
headerfor
key- The first
X-Forwarded-For
header - Peer address of the transport
Get the destination host for this request.
This is determined in the following priority:
Forwarded
headerhost
key- The first
X-Forwarded-Host
header Host
header- URL domain, if any
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.
pub fn insert_header(
&mut self,
name: impl Into<HeaderName>,
values: impl ToHeaderValues
) -> Option<HeaderValues>
pub fn insert_header(
&mut self,
name: impl Into<HeaderName>,
values: impl ToHeaderValues
) -> Option<HeaderValues>
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, 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 mutable reference to value stored in request extensions.
Set a request extension value.
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");
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.
Trait Implementations
Attempt to read from the AsyncRead
into buf
. Read more
Returns a reference to the value corresponding to the supplied name.
Panics
Panics if the name is not present in Request
.
type Output = HeaderValues
type Output = HeaderValues
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
.
type Output = HeaderValues
type Output = HeaderValues
The returned type after indexing.
type Item = (HeaderName, HeaderValues)
type Item = (HeaderName, HeaderValues)
The type of the elements being iterated over.
Auto Trait Implementations
impl<State> !RefUnwindSafe for Request<State>
impl<State> !UnwindSafe for Request<State>
Blanket Implementations
impl<R> AsyncReadExt for R where
R: AsyncRead + ?Sized,
impl<R> AsyncReadExt for R where
R: AsyncRead + ?Sized,
Reads some bytes from the byte stream. Read more
fn read_vectored(
&'a mut self,
bufs: &'a mut [IoSliceMut<'a>]
) -> ReadVectoredFuture<'a, Self> where
Self: Unpin,
fn read_vectored(
&'a mut self,
bufs: &'a mut [IoSliceMut<'a>]
) -> ReadVectoredFuture<'a, Self> where
Self: Unpin,
Like [read()
][AsyncReadExt::read()
], except it reads into a slice of buffers. Read more
fn read_to_end(
&'a mut self,
buf: &'a mut Vec<u8, Global>
) -> ReadToEndFuture<'a, Self> where
Self: Unpin,
fn read_to_end(
&'a mut self,
buf: &'a mut Vec<u8, Global>
) -> ReadToEndFuture<'a, Self> where
Self: Unpin,
fn read_to_string(
&'a mut self,
buf: &'a mut String
) -> ReadToStringFuture<'a, Self> where
Self: Unpin,
fn read_to_string(
&'a mut self,
buf: &'a mut String
) -> ReadToStringFuture<'a, Self> where
Self: Unpin,
fn read_exact(&'a mut self, buf: &'a mut [u8]) -> ReadExactFuture<'a, Self> where
Self: Unpin,
fn read_exact(&'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
Creates an adapter which will read at most limit
bytes from it. 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
fn read_vectored(
&'a mut self,
bufs: &'a mut [IoSliceMut<'a>]
) -> ReadVectored<'a, Self> where
Self: Unpin,
fn read_vectored(
&'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
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
fn read_to_string(&'a mut self, buf: &'a mut String) -> ReadToString<'a, Self> where
Self: Unpin,
fn read_to_string(&'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
Helper method for splitting this read/write object into two halves. Read more
Mutably borrows from an owned value. Read more
Reads some bytes from the byte stream. Read more
fn read_vectored(
&'a mut self,
bufs: &'a mut [IoSliceMut<'a>]
) -> ReadVectoredFuture<'a, Self> where
Self: Unpin,
fn read_vectored(
&'a mut self,
bufs: &'a mut [IoSliceMut<'a>]
) -> ReadVectoredFuture<'a, Self> where
Self: Unpin,
Reads all bytes from the byte stream. Read more
fn read_to_string(
&'a mut self,
buf: &'a mut String
) -> ReadToStringFuture<'a, Self> where
Self: Unpin,
fn read_to_string(
&'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
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
type Output = T
type Output = T
Should always be Self