http_types

Struct Body

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

A streaming HTTP body.

Body represents the HTTP body of both Request and Response. It’s completely streaming, and implements AsyncBufRead to make reading from it both convenient and performant.

Both Request and Response take Body by Into<Body>, which means that passing string literals, byte vectors, but also concrete Body instances are all valid. This makes it easy to create both quick HTTP requests, but also have fine grained control over how bodies are streamed out.

§Examples

use http_types::{Body, Response, StatusCode};
use async_std::io::Cursor;

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

let mut req = Response::new(StatusCode::Ok);
let cursor = Cursor::new("Hello Nori");
let body = Body::from_reader(cursor, Some(10)); // set the body length
req.set_body(body);

§Length

One of the details of Body to be aware of is the length parameter. The value of length is used by HTTP implementations to determine how to treat the stream. If a length is known ahead of time, it’s strongly recommended to pass it.

Casting from Vec<u8>, String, or similar to Body will automatically set the value of length.

§Content Encoding

By default Body will come with a fallback Mime type that is used by Request and Response if no other type has been set, and no other Mime type can be inferred.

It’s strongly recommended to always set a mime type on both the Request and Response, and not rely on the fallback mechanisms. However, they’re still there if you need them.

Implementations§

Source§

impl Body

Source

pub fn empty() -> Self

Create a new empty Body.

The body will have a length of 0, and the Mime type set to application/octet-stream if no other mime type has been set or can be sniffed.

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

let mut req = Response::new(StatusCode::Ok);
req.set_body(Body::empty());
Source

pub fn from_reader( reader: impl AsyncBufRead + Unpin + Send + Sync + 'static, len: Option<usize>, ) -> Self

Create a Body from a reader with an optional length.

The Mime type is set to application/octet-stream if no other mime type has been set or can be sniffed. If a Body has no length, HTTP implementations will often switch over to framed messages such as Chunked Encoding.

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

let mut req = Response::new(StatusCode::Ok);

let cursor = Cursor::new("Hello Nori");
let len = 10;
req.set_body(Body::from_reader(cursor, Some(len)));
Source

pub fn into_reader( self, ) -> Box<dyn AsyncBufRead + Unpin + Send + Sync + 'static>

Get the inner reader from the Body

§Examples
use http_types::Body;
use async_std::io::Cursor;

let cursor = Cursor::new("Hello Nori");
let body = Body::from_reader(cursor, None);
let _ = body.into_reader();
Source

pub fn from_bytes(bytes: Vec<u8>) -> Self

Create a Body from a Vec of bytes.

The Mime type is set to application/octet-stream if no other mime type has been set or can be sniffed. If a Body has no length, HTTP implementations will often switch over to framed messages such as Chunked Encoding.

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

let mut req = Response::new(StatusCode::Ok);

let input = vec![1, 2, 3];
req.set_body(Body::from_bytes(input));
Source

pub async fn into_bytes(self) -> Result<Vec<u8>>

Parse the body into a Vec<u8>.

§Examples
use http_types::Body;

let bytes = vec![1, 2, 3];
let body = Body::from_bytes(bytes);

let bytes: Vec<u8> = body.into_bytes().await?;
assert_eq!(bytes, vec![1, 2, 3]);
Source

pub fn from_string(s: String) -> Self

Create a Body from a String

The Mime type is set to text/plain if no other mime type has been set or can be sniffed. If a Body has no length, HTTP implementations will often switch over to framed messages such as Chunked Encoding.

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

let mut req = Response::new(StatusCode::Ok);

let input = String::from("hello Nori!");
req.set_body(Body::from_string(input));
Source

pub async fn into_string(self) -> Result<String>

Read the body as a string

§Examples
use http_types::Body;
use async_std::io::Cursor;

let cursor = Cursor::new("Hello Nori");
let body = Body::from_reader(cursor, None);
assert_eq!(&body.into_string().await.unwrap(), "Hello Nori");
Source

pub fn from_json(json: &impl Serialize) -> Result<Self>

Creates a Body from a type, serializing it as JSON.

§Mime

The encoding is set to application/json.

§Examples
use http_types::{Body, convert::json};

let body = Body::from_json(&json!({ "name": "Chashu" }));
Source

pub async fn into_json<T: DeserializeOwned>(self) -> Result<T>

Parse the body as JSON, serializing it to a struct.

§Examples
use http_types::Body;
use http_types::convert::{Serialize, Deserialize};

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

let cat = Cat { name: String::from("chashu") };
let body = Body::from_json(&cat)?;

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

pub fn from_form(form: &impl Serialize) -> Result<Self>

Creates a Body from a type, serializing it using form encoding.

§Mime

The encoding is set to application/x-www-form-urlencoded.

§Errors

An error will be returned if the encoding failed.

§Examples
use http_types::Body;
use http_types::convert::{Serialize, Deserialize};

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

let cat = Cat { name: String::from("chashu") };
let body = Body::from_form(&cat)?;

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

pub async fn into_form<T: DeserializeOwned>(self) -> Result<T>

Parse the body from form encoding into a type.

§Errors

An error is returned if the underlying IO stream errors, or if the body could not be deserialized into the type.

§Examples
use http_types::Body;
use http_types::convert::{Serialize, Deserialize};

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

let cat = Cat { name: String::from("chashu") };
let body = Body::from_form(&cat)?;

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

pub async fn from_file<P>(path: P) -> Result<Self>
where P: AsRef<Path>,

Create a Body from a file.

The Mime type set to application/octet-stream if no other mime type has been set or can be sniffed.

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

let mut res = Response::new(StatusCode::Ok);
res.set_body(Body::from_file("/path/to/file").await?);
Source

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

Get the length of the body in bytes.

§Examples
use http_types::Body;
use async_std::io::Cursor;

let cursor = Cursor::new("Hello Nori");
let len = 10;
let body = Body::from_reader(cursor, Some(len));
assert_eq!(body.len(), Some(10));
Source

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

Returns true if the body has a length of zero, and false otherwise.

Source

pub fn mime(&self) -> &Mime

Returns the mime type of this Body.

Source

pub fn set_mime(&mut self, mime: impl Into<Mime>)

Sets the mime type of this Body.

Source

pub fn chain(self, other: Body) -> Self

Create a Body by chaining another Body after this one, consuming both.

If both Body instances have a length, and their sum does not overflow, the resulting Body will have a length.

If both Body instances have the same fallback MIME type, the resulting Body will have the same fallback MIME type; otherwise, the resulting Body will have the fallback MIME type application/octet-stream.

§Examples
use http_types::Body;
use async_std::io::Cursor;

let cursor = Cursor::new("Hello ");
let body = Body::from_reader(cursor, None).chain(Body::from("Nori"));
assert_eq!(&body.into_string().await.unwrap(), "Hello Nori");

Trait Implementations§

Source§

impl AsyncBufRead for Body

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 Body

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 Debug for Body

Source§

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

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

impl<'a> From<&'a [u8]> for Body

Source§

fn from(b: &'a [u8]) -> Self

Converts to this type from the input type.
Source§

impl<'a> From<&'a str> for Body

Source§

fn from(s: &'a str) -> Self

Converts to this type from the input type.
Source§

impl From<Request> for Body

Source§

fn from(req: Request) -> Body

Converts to this type from the input type.
Source§

impl From<String> for Body

Source§

fn from(s: String) -> Self

Converts to this type from the input type.
Source§

impl From<Value> for Body

Source§

fn from(json_value: Value) -> Self

Converts to this type from the input type.
Source§

impl From<Vec<u8>> for Body

Source§

fn from(b: Vec<u8>) -> Self

Converts to this type from the input type.
Source§

impl<'__pin> Unpin for Body
where PinnedFieldsOf<__Origin<'__pin>>: Unpin,

Auto Trait Implementations§

§

impl Freeze for Body

§

impl !RefUnwindSafe for Body

§

impl Send for Body

§

impl Sync for Body

§

impl !UnwindSafe for Body

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