Trait pavex::response::body::TypedBody

source ·
pub trait TypedBody {
    type Body: RawBody<Data = Bytes> + Send + 'static;

    // Required methods
    fn content_type(&self) -> HeaderValue;
    fn body(self) -> Self::Body;
}
Expand description

A trait that ties together a Response body with its expected Content-Type header.

Check out Response::set_typed_body for more details on TypedBody is leveraged when building a Response.

§Implementing TypedBody

You might find yourself implementing TypedBody if none of the implementations provided out-of-the-box by Pavex in the body module satisfies your needs.

You need to specify two things:

  1. The value of the Content-Type header
  2. The low-level representation of your body type

Let’s focus on 2., the trickier bit. You’ll be working with the types in the body::raw module.

§Buffered body

Full<Bytes> is the “canonical” choice if your body is fully buffered in memory before being transmitted over the network.
You need to convert your body type into a buffer (Bytes) which is then wrapped in Full to signal that the entire body is a single “chunk”.

Let’s see how you could implement TypedBody for a String wrapper as a reference example:

use pavex::http::HeaderValue;
use pavex::response::body::{
    TypedBody,
    raw::{Full, Bytes}
};

struct MyString(String);

impl TypedBody for MyString {
    type Body = Full<Bytes>;

    fn content_type(&self) -> HeaderValue {
        HeaderValue::from_static("text/plain; charset=utf-8")
    }

    fn body(self) -> Self::Body {
        Full::new(self.0.into())
    }
}

§Streaming body

Streaming bodies are trickier.
You might need to implement RawBody directly for your body type.

Required Associated Types§

source

type Body: RawBody<Data = Bytes> + Send + 'static

Required Methods§

source

fn content_type(&self) -> HeaderValue

The header value that should be used as Content-Type when returning this Response.

source

fn body(self) -> Self::Body

The actual body type.

It must implement the RawBody trait.

Implementations on Foreign Types§

source§

impl TypedBody for &'static str

source§

impl TypedBody for &'static [u8]

source§

impl TypedBody for Cow<'static, str>

source§

impl TypedBody for Cow<'static, [u8]>

source§

impl TypedBody for String

source§

impl TypedBody for Vec<u8>

Implementors§