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>
impl<State> Request<State>
Sourcepub fn method(&self) -> Method
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?;
Sourcepub fn url(&self) -> &Url
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?;
Sourcepub fn version(&self) -> Option<Version>
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?;
Sourcepub fn peer_addr(&self) -> Option<&str>
pub fn peer_addr(&self) -> Option<&str>
Get the peer socket address for the underlying transport, if that information is available for this request.
Sourcepub fn local_addr(&self) -> Option<&str>
pub fn local_addr(&self) -> Option<&str>
Get the local socket address for the underlying transport, if that information is available for this request.
Sourcepub fn remote(&self) -> Option<&str>
pub fn remote(&self) -> Option<&str>
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
Sourcepub fn host(&self) -> Option<&str>
pub fn host(&self) -> Option<&str>
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
Sourcepub fn content_type(&self) -> Option<Mime>
pub fn content_type(&self) -> Option<Mime>
Sourcepub fn header(&self, key: impl Into<HeaderName>) -> Option<&HeaderValues>
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?;
Sourcepub fn header_mut(
&mut self,
name: impl Into<HeaderName>,
) -> Option<&mut HeaderValues>
pub fn header_mut( &mut self, name: impl Into<HeaderName>, ) -> Option<&mut HeaderValues>
Get a mutable reference to a header.
Sourcepub 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.
Sourcepub fn append_header(
&mut self,
name: impl Into<HeaderName>,
values: impl ToHeaderValues,
)
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.
Sourcepub fn remove_header(
&mut self,
name: impl Into<HeaderName>,
) -> Option<HeaderValues>
pub fn remove_header( &mut self, name: impl Into<HeaderName>, ) -> Option<HeaderValues>
Remove a header.
Sourcepub fn iter_mut(&mut self) -> IterMut<'_>
pub fn iter_mut(&mut self) -> IterMut<'_>
An iterator visiting all header pairs in arbitrary order, with mutable references to the values.
Sourcepub fn header_names(&self) -> Names<'_>
pub fn header_names(&self) -> Names<'_>
An iterator visiting all header names in arbitrary order.
Sourcepub fn header_values(&self) -> Values<'_>
pub fn header_values(&self) -> Values<'_>
An iterator visiting all header values in arbitrary order.
Sourcepub fn ext_mut<T: Send + Sync + 'static>(&mut self) -> Option<&mut T>
pub fn ext_mut<T: Send + Sync + 'static>(&mut self) -> Option<&mut T>
Get a mutable reference to value stored in request extensions.
Sourcepub fn set_ext<T: Send + Sync + 'static>(&mut self, val: T) -> Option<T>
pub fn set_ext<T: Send + Sync + 'static>(&mut self, val: T) -> Option<T>
Set a request extension value.
Sourcepub fn param(&self, key: &str) -> Result<&str>
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?;
Sourcepub fn query<T: DeserializeOwned>(&self) -> Result<T>
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
Sourcepub fn take_body(&mut self) -> Body
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.
Sourcepub async fn body_bytes(&mut self) -> Result<Vec<u8>>
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?;
Sourcepub async fn body_string(&mut self) -> Result<String>
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?;
Sourcepub async fn body_json<T: DeserializeOwned>(&mut self) -> Result<T>
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.
Sourcepub async fn body_form<T: DeserializeOwned>(&mut self) -> Result<T>
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
returns a Cookie
by name of the cookie.
Sourcepub fn session(&self) -> &Session
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.
Sourcepub fn session_mut(&mut self) -> &mut Session
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.
Sourcepub fn len(&self) -> Option<usize>
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.
Trait Implementations§
Source§impl<State> AsyncRead for Request<State>
impl<State> AsyncRead for Request<State>
Source§impl<State> Index<&str> for Request<State>
impl<State> Index<&str> for Request<State>
Source§fn index(&self, name: &str) -> &HeaderValues
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
type Output = HeaderValues
Source§impl<State> Index<HeaderName> for Request<State>
impl<State> Index<HeaderName> for Request<State>
Source§fn index(&self, name: HeaderName) -> &HeaderValues
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
type Output = HeaderValues
Source§impl<'a, State> IntoIterator for &'a Request<State>
impl<'a, State> IntoIterator for &'a Request<State>
Source§impl<'a, State> IntoIterator for &'a mut Request<State>
impl<'a, State> IntoIterator for &'a mut Request<State>
Source§impl<State> IntoIterator for Request<State>
impl<State> IntoIterator for Request<State>
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<R> AsyncReadExt for R
impl<R> AsyncReadExt for R
Source§fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> ReadFuture<'a, Self>where
Self: Unpin,
fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> ReadFuture<'a, Self>where
Self: Unpin,
Source§fn read_vectored<'a>(
&'a mut self,
bufs: &'a mut [IoSliceMut<'a>],
) -> ReadVectoredFuture<'a, Self>where
Self: Unpin,
fn read_vectored<'a>(
&'a mut self,
bufs: &'a mut [IoSliceMut<'a>],
) -> ReadVectoredFuture<'a, Self>where
Self: Unpin,
Source§fn read_to_end<'a>(
&'a mut self,
buf: &'a mut Vec<u8>,
) -> ReadToEndFuture<'a, Self>where
Self: Unpin,
fn read_to_end<'a>(
&'a mut self,
buf: &'a mut Vec<u8>,
) -> ReadToEndFuture<'a, Self>where
Self: Unpin,
Source§fn read_to_string<'a>(
&'a mut self,
buf: &'a mut String,
) -> ReadToStringFuture<'a, Self>where
Self: Unpin,
fn read_to_string<'a>(
&'a mut self,
buf: &'a mut String,
) -> ReadToStringFuture<'a, Self>where
Self: Unpin,
Source§fn read_exact<'a>(&'a mut self, buf: &'a mut [u8]) -> ReadExactFuture<'a, Self>where
Self: Unpin,
fn read_exact<'a>(&'a mut self, buf: &'a mut [u8]) -> ReadExactFuture<'a, Self>where
Self: Unpin,
buf
. Read moreSource§fn take(self, limit: u64) -> Take<Self>where
Self: Sized,
fn take(self, limit: u64) -> Take<Self>where
Self: Sized,
limit
bytes from it. Read moreSource§impl<R> AsyncReadExt for R
impl<R> AsyncReadExt for R
Source§fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> ReadFuture<'a, Self>where
Self: Unpin,
fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> ReadFuture<'a, Self>where
Self: Unpin,
Source§fn read_vectored<'a>(
&'a mut self,
bufs: &'a mut [IoSliceMut<'a>],
) -> ReadVectoredFuture<'a, Self>where
Self: Unpin,
fn read_vectored<'a>(
&'a mut self,
bufs: &'a mut [IoSliceMut<'a>],
) -> ReadVectoredFuture<'a, Self>where
Self: Unpin,
Source§fn read_to_end<'a>(
&'a mut self,
buf: &'a mut Vec<u8>,
) -> ReadToEndFuture<'a, Self>where
Self: Unpin,
fn read_to_end<'a>(
&'a mut self,
buf: &'a mut Vec<u8>,
) -> ReadToEndFuture<'a, Self>where
Self: Unpin,
Source§fn read_to_string<'a>(
&'a mut self,
buf: &'a mut String,
) -> ReadToStringFuture<'a, Self>where
Self: Unpin,
fn read_to_string<'a>(
&'a mut self,
buf: &'a mut String,
) -> ReadToStringFuture<'a, Self>where
Self: Unpin,
Source§fn read_exact<'a>(&'a mut self, buf: &'a mut [u8]) -> ReadExactFuture<'a, Self>where
Self: Unpin,
fn read_exact<'a>(&'a mut self, buf: &'a mut [u8]) -> ReadExactFuture<'a, Self>where
Self: Unpin,
buf
. Read moreSource§fn take(self, limit: u64) -> Take<Self>where
Self: Sized,
fn take(self, limit: u64) -> Take<Self>where
Self: Sized,
limit
bytes from it. Read moreSource§impl<R> AsyncReadExt for R
impl<R> AsyncReadExt for R
Source§fn chain<R>(self, next: R) -> Chain<Self, R>
fn chain<R>(self, next: R) -> Chain<Self, R>
Source§fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> Read<'a, Self>where
Self: Unpin,
fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> Read<'a, Self>where
Self: Unpin,
buf
in asynchronous
manner, returning a future type. Read moreSource§fn read_vectored<'a>(
&'a mut self,
bufs: &'a mut [IoSliceMut<'a>],
) -> ReadVectored<'a, Self>where
Self: Unpin,
fn read_vectored<'a>(
&'a mut self,
bufs: &'a mut [IoSliceMut<'a>],
) -> ReadVectored<'a, Self>where
Self: Unpin,
AsyncRead
into bufs
using vectored
IO operations. Read moreSource§fn read_exact<'a>(&'a mut self, buf: &'a mut [u8]) -> ReadExact<'a, Self>where
Self: Unpin,
fn read_exact<'a>(&'a mut self, buf: &'a mut [u8]) -> ReadExact<'a, Self>where
Self: Unpin,
buf
,
returning an error if end of file (EOF) is hit sooner. Read moreSource§fn read_to_end<'a>(&'a mut self, buf: &'a mut Vec<u8>) -> ReadToEnd<'a, Self>where
Self: Unpin,
fn read_to_end<'a>(&'a mut self, buf: &'a mut Vec<u8>) -> ReadToEnd<'a, Self>where
Self: Unpin,
AsyncRead
. Read moreSource§fn read_to_string<'a>(
&'a mut self,
buf: &'a mut String,
) -> ReadToString<'a, Self>where
Self: Unpin,
fn read_to_string<'a>(
&'a mut self,
buf: &'a mut String,
) -> ReadToString<'a, Self>where
Self: Unpin,
AsyncRead
. Read moreSource§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> ReadExt for T
impl<T> ReadExt for T
Source§fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> ReadFuture<'a, Self>where
Self: Unpin,
fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> ReadFuture<'a, Self>where
Self: Unpin,
Source§fn read_vectored<'a>(
&'a mut self,
bufs: &'a mut [IoSliceMut<'a>],
) -> ReadVectoredFuture<'a, Self>where
Self: Unpin,
fn read_vectored<'a>(
&'a mut self,
bufs: &'a mut [IoSliceMut<'a>],
) -> ReadVectoredFuture<'a, Self>where
Self: Unpin,
Source§fn read_to_end<'a>(
&'a mut self,
buf: &'a mut Vec<u8>,
) -> ReadToEndFuture<'a, Self>where
Self: Unpin,
fn read_to_end<'a>(
&'a mut self,
buf: &'a mut Vec<u8>,
) -> ReadToEndFuture<'a, Self>where
Self: Unpin,
Source§fn read_to_string<'a>(
&'a mut self,
buf: &'a mut String,
) -> ReadToStringFuture<'a, Self>where
Self: Unpin,
fn read_to_string<'a>(
&'a mut self,
buf: &'a mut String,
) -> ReadToStringFuture<'a, Self>where
Self: Unpin,
Source§fn read_exact<'a>(&'a mut self, buf: &'a mut [u8]) -> ReadExactFuture<'a, Self>where
Self: Unpin,
fn read_exact<'a>(&'a mut self, buf: &'a mut [u8]) -> ReadExactFuture<'a, Self>where
Self: Unpin,
buf
. Read moreSource§fn take(self, limit: u64) -> Take<Self>where
Self: Sized,
fn take(self, limit: u64) -> Take<Self>where
Self: Sized,
limit
bytes from it. Read moreSource§fn by_ref(&mut self) -> &mut Selfwhere
Self: Sized,
fn by_ref(&mut self) -> &mut Selfwhere
Self: Sized,
Read
. Read more