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

HTTP request.

请求、路由参数以及访问请求的各种方式。 中间件和endpoints之间的通信

Implementations§

source§

impl<State> Request<State>

source

pub fn method(&self) -> Method

访问请求的HTTP方法。

Examples
use summer_boot::Request;

let mut app = summer_boot::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

访问请求的完整URI方法。

source

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

访问请求的HTTP版本。

Examples
use summer_boot::Request;

let mut app = summer_boot::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>

获取基础传输的socket地址

source

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

获取基础传输的本地地址

source

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

获取此请求的远程地址。

按以下优先级确定:

  1. Forwarded head for key
  2. 第一个 X-Forwarded-For header
  3. 传输的对等地址
source

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

获取此请求的目标主机。

按以下优先级确定:

  1. Forwarded header host key
  2. 第一个 X-Forwarded-Host header
  3. Host header
  4. URL域
source

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

以“Mime”形式获取请求内容类型。

这将获取请求 Content-Type header。

source

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

获取HTTP header.

Examples
use summer_boot::Request;

let mut app = summer_boot::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>

获取标题的可变引用。

source

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

设置一个 HTTP header.

source

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

将header添加到headers。

insert 不同,此函数不会重写标头的内容,而是插入 如果没有header。添加到现有的headers列表中。

source

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

移除一个 header.

source

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

以任意顺序访问所有header的迭代。

source

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

迭代器以任意顺序访问所有header,并对值进行可变引用。

source

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

以任意顺序访问所有header名称的迭代。

source

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

以任意顺序访问所有header值的迭代。

source

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

获取请求扩展值。

source

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

获取对存储在请求扩展中的值的可变引用。

source

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

设置请求扩展值。

source

pub fn state(&self) -> &State

访问应用程序范围的状态。

source

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

按名称提取和解析路由参数。

&str 形式返回参数,该参数是从此 Request 借用的。

名称应不包括引用 :

Errors

如果 key 不是路由的有效参数,则返回错误。

Examples
use summer_boot::{Request, Result};

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

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

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

从路由中提取通配符(如果存在)

&str 形式返回参数,该参数是从此 Request 借用的。

Examples
use summer_boot::{Request, Result};

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

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

pub fn query<'de, T: Deserialize<'de>>(&'de self) -> Result<T>

使用serde_qs将URL查询组件解析为结构 将整个查询作为未解析的字符串获取,使用 request.url().query()

Examples
use std::collections::HashMap;
use summer_boot::http_types::{self, convert::Deserialize};
use summer_boot::Request;

// 所有权结构:

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

let req: Request<()> = http_types::Request::get("https://baidu.com/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");

// 使用借用s:

#[derive(Deserialize)]
struct Query<'q> {
    format: &'q str,
}

let req: Request<()> = http_types::Request::get("https://httpbin.org/get?format=bananna").into();
let Query { format } = req.query().unwrap();
assert_eq!(format, "bananna");
source

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

设置body读取

source

pub fn take_body(&mut self) -> Body

处理请求 Body

可以在获取或读取body后调用此方法, 但是将返回一个空的Body.

这对于通过AsyncReader或AsyncBufReader有用。

source

pub async fn body_bytes(&mut self) -> Result<Vec<u8>>

将整个请求body读取字节缓冲区。

可以在读取body后调用此方法,但生成空缓冲区。

Errors

读取body时遇到的任何I/O错误都会立即返回错误 Err

Examples
use summer_boot::Request;

let mut app = summer_boot::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>

将整个请求body读取字符串。

可以在读取body后调用此方法,但生成空缓冲区。

Errors

读取body时遇到的任何I/O错误都会立即返回错误 Err

如果body不能解释有效的UTF-8,则返回 Err

Examples
use summer_boot::Request;

let mut app = summer_boot::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>

通过json读取并反序列化整个请求body。

Errors

读取body时遇到的任何I/O错误都会立即返回错误 Err

如果无法将body解释为目标类型 T 的有效json,则返回 Err

source

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

将请求主体解析为表单

use serde::Deserialize;
let mut app = summer_boot::new();

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

app.at("/").post(|mut req: summer_boot::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/test/api -d "name=chashu&legs=4"
// hello, chashu! i've put in an order for 4 shoes

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

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

获取body流的长度(如果已设置)。

将固定大小的对象传递到作为body时,会设置此值(比如字符串)。 或者缓冲区。 此API的使用应检查此值,决定是否使用 Chunked 设置响应长度

source

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

如果请求的设置body流长度为零,则返回 true,否则返回 false

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: 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> From<Request<State>> for Request

source§

fn from(request: Request<State>) -> Request

Converts to this type from the input type.
source§

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

source§

fn from(request: Request<State>) -> Response

Converts to this type from the input type.
source§

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

source§

fn from(request: Request) -> Request<State>

Converts to this type from the input type.
source§

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

source§

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

返回对与提供的名称相对应的值的引用。

Panics

如果 Request 中没有该名称,则会panic

§

type Output = HeaderValues

The returned type after indexing.
source§

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

source§

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

返回对与提供的名称相对应的值的引用。

Panics

如果 Request 中没有该名称,则会panic

§

type Output = HeaderValues

The returned type after indexing.
source§

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

§

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

The type of the elements being iterated over.
§

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>

§

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

The type of the elements being iterated over.
§

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

返回对其余项的引用的迭代.

§

type Item = (HeaderName, HeaderValues)

The type of the elements being iterated over.
§

type IntoIter = IntoIter

Which kind of iterator are we turning this into?
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
§

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<'__pin, State> Unpin for Request<State>
where __Origin<'__pin, State>: Unpin,

Auto Trait Implementations§

§

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
§

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

§

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
§

fn read_vectored<'a>( &'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>( &'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
§

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
§

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
§

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

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

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

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

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
§

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
§

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

§

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
§

fn read_vectored<'a>( &'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>( &'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
§

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
§

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
§

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

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

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

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

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
§

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

§

impl<T> Instrument for T

§

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

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

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

§

type Output = T

Should always be Self
source§

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

§

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>,

§

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

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

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

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
§

fn with_current_subscriber(self) -> WithDispatch<Self>

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