http_types

Struct Response

Source
pub struct Response { /* private fields */ }
Expand description

An HTTP response.

§Examples

use http_types::{Response, StatusCode};

let mut res = Response::new(StatusCode::Ok);
res.set_body("Hello, Nori!");

Implementations§

Source§

impl Response

Source

pub fn new<S>(status: S) -> Self
where S: TryInto<StatusCode>, S::Error: Debug,

Create a new response.

Source

pub fn status(&self) -> StatusCode

Get the status

Source

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

Get a mutable reference to a header.

Source

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

Get an HTTP header.

Source

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

Remove a header.

Source

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

Set an HTTP header.

§Examples
use http_types::{Method, Response, StatusCode, Url};

let mut req = Response::new(StatusCode::Ok);
req.insert_header("Content-Type", "text/plain");
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.

§Examples
use http_types::{Response, StatusCode};

let mut res = Response::new(StatusCode::Ok);
res.append_header("Content-Type", "text/plain");
Source

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

Set the body reader.

§Examples
use http_types::{Response, StatusCode};

let mut res = Response::new(StatusCode::Ok);
res.set_body("Hello, Nori!");
Source

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

Replace the response body with a new body, returning the old body.

§Examples
use http_types::{Body, Method, Response, StatusCode, Url};

let mut req = Response::new(StatusCode::Ok);
req.set_body("Hello, Nori!");

let mut body: Body = req.replace_body("Hello, Chashu");

let mut string = String::new();
body.read_to_string(&mut string).await?;
assert_eq!(&string, "Hello, Nori!");
Source

pub fn swap_body(&mut self, body: &mut Body)

Swaps the value of the body with another body, without deinitializing either one.

§Examples
use http_types::{Body, Method, Response, StatusCode, Url};

let mut req = Response::new(StatusCode::Ok);
req.set_body("Hello, Nori!");

let mut body = "Hello, Chashu!".into();
req.swap_body(&mut body);

let mut string = String::new();
body.read_to_string(&mut string).await?;
assert_eq!(&string, "Hello, Nori!");
Source

pub fn take_body(&mut self) -> Body

Take the response body, replacing it with an empty body.

§Examples
use http_types::{Body, Method, Response, StatusCode, Url};

let mut req = Response::new(StatusCode::Ok);
req.set_body("Hello, Nori!");
let mut body: Body = req.take_body();

let mut string = String::new();
body.read_to_string(&mut string).await?;
assert_eq!(&string, "Hello, Nori!");
Source

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

Read the body as a string.

This consumes the response. If you want to read the body without consuming the response, consider using the take_body method and then calling Body::into_string or using the Response’s AsyncRead implementation to read the body.

§Examples
use async_std::io::Cursor;
use http_types::{Body, Method, Response, StatusCode, Url};

let mut res = Response::new(StatusCode::Ok);
let cursor = Cursor::new("Hello Nori");
let body = Body::from_reader(cursor, None);
res.set_body(body);
assert_eq!(&res.body_string().await.unwrap(), "Hello Nori");
Source

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

Read the body as bytes.

This consumes the Response. If you want to read the body without consuming the response, consider using the take_body method and then calling Body::into_bytes or using the Response’s AsyncRead implementation to read the body.

§Examples
use http_types::{Body, Method, Response, StatusCode, Url};

let bytes = vec![1, 2, 3];
let mut res = Response::new(StatusCode::Ok);
res.set_body(Body::from_bytes(bytes));

let bytes = res.body_bytes().await?;
assert_eq!(bytes, vec![1, 2, 3]);
Source

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

Read the body as JSON.

This consumes the response. If you want to read the body without consuming the response, consider using the take_body method and then calling Body::into_json or using the Response’s AsyncRead implementation to read the body.

§Examples
use http_types::convert::{Deserialize, Serialize};
use http_types::{Body, Method, Response, StatusCode, Url};

#[derive(Debug, Serialize, Deserialize)]
struct Cat {
    name: String,
}

let cat = Cat {
    name: String::from("chashu"),
};
let mut res = Response::new(StatusCode::Ok);
res.set_body(Body::from_json(&cat)?);

let cat: Cat = res.body_json().await?;
assert_eq!(&cat.name, "chashu");
Source

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

Read the body as x-www-form-urlencoded.

This consumes the request. If you want to read the body without consuming the request, consider using the take_body method and then calling Body::into_json or using the Response’s AsyncRead implementation to read the body.

§Examples
use http_types::convert::{Deserialize, Serialize};
use http_types::{Body, Method, Response, StatusCode, Url};

#[derive(Debug, Serialize, Deserialize)]
struct Cat {
    name: String,
}

let cat = Cat {
    name: String::from("chashu"),
};
let mut res = Response::new(StatusCode::Ok);
res.set_body(Body::from_form(&cat)?);

let cat: Cat = res.body_form().await?;
assert_eq!(&cat.name, "chashu");
Source

pub fn set_content_type(&mut self, mime: Mime) -> Option<HeaderValues>

Set the response MIME.

Source

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

Get the current content type

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 set length of the body stream is zero, false otherwise.

Source

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

Get the HTTP version, if one has been set.

§Examples
use http_types::{Response, StatusCode, Version};

let mut res = Response::new(StatusCode::Ok);
assert_eq!(res.version(), None);

res.set_version(Some(Version::Http2_0));
assert_eq!(res.version(), Some(Version::Http2_0));
Source

pub fn set_peer_addr(&mut self, peer_addr: Option<impl ToString>)

Sets a string representation of the peer address that this response was sent to. This might take the form of an ip/fqdn and port or a local socket address.

Source

pub fn set_local_addr(&mut self, local_addr: Option<impl ToString>)

Sets a string representation of the local address that this response was sent on. This might take the form of an ip/fqdn and port, or a local socket address.

Source

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

Get the peer socket address for the underlying transport, if appropriate

Source

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

Get the local socket address for the underlying transport, if appropriate

Source

pub fn set_version(&mut self, version: Option<Version>)

Set the HTTP version.

§Examples
use http_types::{Response, StatusCode, Version};

let mut res = Response::new(StatusCode::Ok);
res.set_version(Some(Version::Http2_0));
Source

pub fn set_status(&mut self, status: StatusCode)

Set the status.

Source

pub fn send_trailers(&mut self) -> Sender

Sends trailers to the a receiver.

Source

pub fn recv_trailers(&mut self) -> Receiver

Receive trailers from a sender.

Source

pub fn has_trailers(&self) -> bool

Returns true if sending trailers is in progress.

Source

pub fn send_upgrade(&mut self) -> Sender

Available on unstable only.

Sends an upgrade connection to the a receiver.

Source

pub async fn recv_upgrade(&mut self) -> Receiver

Available on unstable only.

Receive an upgraded connection from a sender.

Source

pub fn has_upgrade(&self) -> bool

Available on unstable only.

Returns true if a protocol upgrade is in progress.

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(&self) -> &Extensions

Returns a reference to the existing local.

Source

pub fn ext_mut(&mut self) -> &mut Extensions

Returns a mutuable reference to the existing local state.

§Examples
use http_types::{Response, StatusCode, Version};

let mut res = Response::new(StatusCode::Ok);
res.ext_mut().insert("hello from the extension");
assert_eq!(res.ext().get(), Some(&"hello from the extension"));

Trait Implementations§

Source§

impl AsMut<Headers> for Response

Source§

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

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

impl AsRef<Headers> for Response

Source§

fn as_ref(&self) -> &Headers

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

impl AsyncBufRead for Response

Source§

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

Attempt to return the contents of the internal buffer, filling it with more data from the inner reader if it is empty. Read more
Source§

fn consume(self: Pin<&mut Self>, amt: usize)

Tells this buffer that amt bytes have been consumed from the buffer, so they should no longer be returned in calls to poll_read. Read more
Source§

impl AsyncRead for Response

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 Clone for Response

Source§

fn clone(&self) -> Self

Clone the response, resolving the body to Body::empty() and removing extensions.

1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Response

Source§

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

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

impl From<()> for Response

Source§

fn from(_: ()) -> Self

Converts to this type from the input type.
Source§

impl From<StatusCode> for Response

Source§

fn from(s: StatusCode) -> Self

Converts to this type from the input type.
Source§

impl<T> From<T> for Response
where T: Into<Body>,

Source§

fn from(value: T) -> Self

Converts to this type from the input type.
Source§

impl Index<&str> for Response

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

Source§

type Output = HeaderValues

The returned type after indexing.
Source§

impl Index<HeaderName> for Response

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

Source§

type Output = HeaderValues

The returned type after indexing.
Source§

impl<'a> IntoIterator for &'a Response

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> IntoIterator for &'a mut Response

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 IntoIterator for Response

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

Auto Trait Implementations§

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

Source§

fn fill_buf(&mut self) -> FillBuf<'_, Self>
where Self: Unpin,

Returns the contents of the internal buffer, filling it with more data if empty. Read more
Source§

fn consume(&mut self, amt: usize)
where Self: Unpin,

Consumes amt buffered bytes. Read more
Source§

fn read_until<'a>( &'a mut self, byte: u8, buf: &'a mut Vec<u8>, ) -> ReadUntilFuture<'a, Self>
where Self: Unpin,

Reads all bytes and appends them into buf until the delimiter byte or EOF is found. Read more
Source§

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

Reads all bytes and appends them into buf until a newline (the 0xA byte) or EOF is found. Read more
Source§

fn lines(self) -> Lines<Self>
where Self: Sized + Unpin,

Returns a stream over the lines of this byte stream. Read more
Source§

fn split(self, byte: u8) -> Split<Self>
where Self: Sized,

Returns a stream over the contents of this reader split on the specified byte. Read more
Source§

impl<R> AsyncBufReadExt for R
where R: AsyncBufRead + ?Sized,

Source§

fn fill_buf(&mut self) -> FillBuf<'_, Self>
where Self: Unpin,

Returns the contents of the internal buffer, filling it with more data if empty. Read more
Source§

fn consume(&mut self, amt: usize)
where Self: Unpin,

Consumes amt buffered bytes. Read more
Source§

fn read_until<'a>( &'a mut self, byte: u8, buf: &'a mut Vec<u8>, ) -> ReadUntilFuture<'a, Self>
where Self: Unpin,

Reads all bytes and appends them into buf until the delimiter byte or EOF is found. Read more
Source§

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

Reads all bytes and appends them into buf until a newline (the 0xA byte) or EOF is found. Read more
Source§

fn lines(self) -> Lines<Self>
where Self: Sized,

Returns a stream over the lines of this byte stream. Read more
Source§

fn split(self, byte: u8) -> Split<Self>
where Self: Sized,

Returns a stream over the contents of this reader split on the specified byte. 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<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> BufReadExt for T
where T: AsyncBufRead + ?Sized,

Source§

fn read_until<'a>( &'a mut self, byte: u8, buf: &'a mut Vec<u8>, ) -> ReadUntilFuture<'a, Self>
where Self: Unpin,

Reads all bytes into buf until the delimiter byte or EOF is reached. Read more
Source§

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

Reads all bytes and appends them into buf until a newline (the 0xA byte) is reached. Read more
Source§

fn lines(self) -> Lines<Self>
where Self: Sized + Unpin,

Returns a stream over the lines of this byte stream. Read more
Source§

fn split(self, byte: u8) -> Split<Self>
where Self: Sized,

Returns a stream over the contents of this reader split on the byte byte. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. 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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
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,

Source§

impl<T> MaybeSendSync for T