Struct pavex::response::Response

source ·
pub struct Response { /* private fields */ }
Expand description

Represents an HTTP response.

use pavex::response::Response;
use pavex::http::{HeaderValue, header::SERVER};

// Create a new response with:
// - status code `OK`
// - HTTP version `HTTP/1.1`
// - the `Server` header set to `Pavex`
// - the `Content-Type` header set to `text/plain; charset=utf-8`
// - the body set to `Hello, world!`
let response = Response::ok()
    .insert_header(SERVER, HeaderValue::from_static("Pavex"))
    .set_typed_body("Hello, world!");

The response is composed of a head (ResponseHead) and an optional body.

Check out Response::new for details on how to build a new Response.
You might also want to check out the following methods to further customize your response:

There are other methods available on Response that you might find useful, but the ones listed above are the most commonly used and should be enough to get you started.

Implementations§

source§

impl Response

source

pub fn new(status_code: StatusCode) -> Self

Build a new Response with the given status code.
The HTTP version is set to HTTP 1.1, there are no headers and the body is empty.

§Example
use pavex::http::StatusCode;
use pavex::response::Response;
     
let response = Response::new(StatusCode::OK);
§Alternatives

Pavex’s provides a set of shorthands for building a new Response using well-known status code. For example, the following code is equivalent to the example above:

use pavex::response::Response;
     
let response = Response::ok();

Check out Response’s API documentation for a complete list of all the supported shorthands.

source§

impl Response

source

pub fn set_status(self, status: StatusCode) -> Self

Change the status code of the Response.

§Example
use pavex::http::StatusCode;
use pavex::response::Response;

let mut response = Response::ok();
assert_eq!(response.status(), StatusCode::OK);

// Change the status code to `CREATED`.
response = response.set_status(StatusCode::CREATED);
assert_eq!(response.status(), StatusCode::CREATED);
source

pub fn set_version(self, version: Version) -> Self

Change the HTTP version of the Response.

§Example
use pavex::http::Version;
use pavex::response::Response;

let mut response = Response::ok();
// By default, the HTTP version is HTTP/1.1.
assert_eq!(response.version(), Version::HTTP_11);

// Change the HTTP version to HTTP/2.
response = response.set_version(Version::HTTP_2);
assert_eq!(response.version(), Version::HTTP_2);
source

pub fn append_header(self, key: HeaderName, value: HeaderValue) -> Self

Append a value to a Response header.

If the header is not present, it is added with the given value.
If the header is present, the value is appended to the end of the comma-separated list of existing values for that header.

§Example
use pavex::http::{header::HOST, HeaderValue};
use pavex::response::Response;

let mut response = Response::ok();
assert!(response.headers().get("host").is_none());

// Append a value to the `host` header.
let value = HeaderValue::from_static("world");
response = response.append_header(HOST, value);

let headers: Vec<_> = response.headers().get_all("host").iter().collect();
assert_eq!(headers.len(), 1);
assert_eq!(headers[0], "world");

// Append another value to the `host` header.
let value = HeaderValue::from_static("earth");
response = response.append_header(HOST, value);

let headers: Vec<_> = response.headers().get_all("host").iter().collect();
assert_eq!(headers.len(), 2);
assert_eq!(headers[0], "world");
assert_eq!(headers[1], "earth");
§Alternatives

If you want to replace the value of a header instead of appending to it, use insert_header instead.

source

pub fn insert_header(self, key: HeaderName, value: HeaderValue) -> Self

Insert a header value into the Response.

If the header key is not present, it is added with the given value. If the header key is present, its value is replaced with the given value.

§Example
use pavex::http::{header::HOST, HeaderValue};
use pavex::response::Response;
     
let mut response = Response::ok();
assert!(response.headers().get("host").is_none());
     
// Insert a value into the `host` header.
let value = HeaderValue::from_static("world");
response = response.insert_header(HOST, value);

let headers: Vec<_> = response.headers().get_all("host").iter().collect();
assert_eq!(headers.len(), 1);
assert_eq!(headers[0], "world");

// Insert another value into the `host` header.
let value = HeaderValue::from_static("earth");
response = response.insert_header(HOST, value);
     
let headers: Vec<_> = response.headers().get_all("host").iter().collect();
assert_eq!(headers.len(), 1);
assert_eq!(headers[0], "earth");
§Alternatives

If you want to append to the current header value instead of replacing it, use append_header instead.

source

pub fn set_typed_body<NewBody>(self, body: NewBody) -> Response
where NewBody: TypedBody, <<NewBody as TypedBody>::Body as RawBody>::Error: Into<Box<dyn Error + Send + Sync>>,

Set the Response body.

The provided body must implement the TypedBody trait.
The Content-Type header is automatically set to the value returned by TypedBody::content_type.

If a body is already set, it is replaced.

§Example
use pavex::response::{Response, body::Html};
use pavex::http::header::CONTENT_TYPE;

let typed_body = "Hello, world!";
let response = Response::ok().set_typed_body(typed_body);

// The `Content-Type` header is set automatically
// when using `set_typed_body`.
assert_eq!(response.headers()[CONTENT_TYPE], "text/plain; charset=utf-8");
§Built-in TypedBody implementations

Pavex provides several implementations of TypedBody out of the box, to cover the most common use cases:

Check out the body sub-module for an exhaustive list.

§Raw body

If you don’t want Pavex to automatically set the Content-Type header, you might want to use Response::set_raw_body instead.

source

pub fn set_raw_body<NewBody>(self, body: NewBody) -> Response
where NewBody: RawBody<Data = Bytes> + Send + 'static, <NewBody as RawBody>::Error: Into<Box<dyn Error + Send + Sync>>,

Set the body of the Response to the given value, without setting the Content-Type header.

This method should only be used if you need fine-grained control over the Content-Type header or the body type. In all other circumstances, use set_typed_body.

§Example
use pavex::response::Response;
use pavex::response::body::raw::{Bytes, Full};
use pavex::http::header::CONTENT_TYPE;
     
let raw_body: Full<Bytes> = Full::new("Hello, world!".into());
let response = Response::ok().set_raw_body(raw_body);

// The `Content-Type` header is not set automatically
// when using `set_raw_body`.
assert_eq!(response.headers().get(CONTENT_TYPE), None);
source

pub fn body_mut(&mut self) -> &mut ResponseBody

Get a mutable reference to the Response body.

source

pub fn headers_mut(&mut self) -> &mut HeaderMap

Get a mutable reference to the Response headers.

§Example
use pavex::response::Response;
use pavex::http::{header::CONTENT_TYPE, HeaderValue};
use mime::TEXT_PLAIN_UTF_8;

let mut response = Response::ok();

// Get a mutable reference to the headers.
let headers = response.headers_mut();

// Insert a header.
let value = HeaderValue::from_static(TEXT_PLAIN_UTF_8.as_ref());
headers.insert(CONTENT_TYPE, value);

assert_eq!(headers.len(), 1);

// Remove a header.
headers.remove(CONTENT_TYPE);

assert!(headers.is_empty());
source§

impl Response

source

pub fn status(&self) -> StatusCode

Get a reference to the Response status code.

§Example
use pavex::{http::StatusCode, response::Response};

let response = Response::bad_request();
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
§Mutation

Check out Response::set_status if you need to modify the status code of the Response.

source

pub fn version(&self) -> Version

Get a reference to the version of the HTTP protocol used by the Response.

§Example
use pavex::http::Version;
use pavex::response::Response;

let mut response = Response::ok();
// By default, the HTTP version is HTTP/1.1.
assert_eq!(response.version(), Version::HTTP_11);
§Mutation

Check out Response::set_version if you need to modify the HTTP protocol version used by the Response.

source

pub fn headers(&self) -> &HeaderMap

Get a reference to the Response headers.

§Example
use pavex::http::{header::{HOST, SERVER}, HeaderValue};
use pavex::response::Response;
     
let response = Response::ok()
    .append_header(HOST, HeaderValue::from_static("world"))
    .append_header(HOST, HeaderValue::from_static("earth"))
    .insert_header(SERVER, HeaderValue::from_static("Pavex"));

let headers = response.headers();
assert_eq!(headers.len(), 3);

let host_values: Vec<_> = response.headers().get_all("host").iter().collect();
assert_eq!(host_values.len(), 2);
assert_eq!(host_values[0], "world");
assert_eq!(host_values[1], "earth");

assert_eq!(headers[SERVER], "Pavex");
§Mutation

If you need to modify the Response headers, check out:

source

pub fn body(&self) -> &ResponseBody

Get a reference to the Response body.

§Mutation

If you need to modify the Response body, check out:

source§

impl Response

source

pub fn into_parts(self) -> (ResponseHead, ResponseBody)

Break down the Response into its two components: the ResponseHead and the body.

This method consumes the Response.

You can use Response::from_parts to reconstruct a Response from a ResponseHead and a body.

source

pub fn from_parts(head: ResponseHead, body: ResponseBody) -> Self

Build a Response from its two components: the ResponseHead and the body.

You can use Response::into_parts to decompose a Response from a ResponseHead and a body.

source§

impl Response

Shorthand for building a new Response using a well-known status code.

source

pub fn continue_() -> Response

Start building a new Response with CONTINUE as status code.

source

pub fn switching_protocols() -> Response

Start building a new Response with SWITCHING_PROTOCOLS as status code.

source

pub fn processing() -> Response

Start building a new Response with PROCESSING as status code.

source

pub fn ok() -> Response

Start building a new Response with OK as status code.

source

pub fn created() -> Response

Start building a new Response with CREATED as status code.

source

pub fn accepted() -> Response

Start building a new Response with ACCEPTED as status code.

source

pub fn non_authoritative_information() -> Response

Start building a new Response with NON_AUTHORITATIVE_INFORMATION as status code.

source

pub fn no_content() -> Response

Start building a new Response with NO_CONTENT as status code.

source

pub fn reset_content() -> Response

Start building a new Response with RESET_CONTENT as status code.

source

pub fn partial_content() -> Response

Start building a new Response with PARTIAL_CONTENT as status code.

source

pub fn multi_status() -> Response

Start building a new Response with MULTI_STATUS as status code.

source

pub fn already_reported() -> Response

Start building a new Response with ALREADY_REPORTED as status code.

source

pub fn multiple_choices() -> Response

Start building a new Response with MULTIPLE_CHOICES as status code.

source

pub fn moved_permanently() -> Response

Start building a new Response with MOVED_PERMANENTLY as status code.

source

pub fn found() -> Response

Start building a new Response with FOUND as status code.

source

pub fn see_other() -> Response

Start building a new Response with SEE_OTHER as status code.

source

pub fn not_modified() -> Response

Start building a new Response with NOT_MODIFIED as status code.

source

pub fn use_proxy() -> Response

Start building a new Response with USE_PROXY as status code.

source

pub fn temporary_redirect() -> Response

Start building a new Response with TEMPORARY_REDIRECT as status code.

source

pub fn permanent_redirect() -> Response

Start building a new Response with PERMANENT_REDIRECT as status code.

source

pub fn bad_request() -> Response

Start building a new Response with BAD_REQUEST as status code.

source

pub fn not_found() -> Response

Start building a new Response with NOT_FOUND as status code.

source

pub fn unauthorized() -> Response

Start building a new Response with UNAUTHORIZED as status code.

source

pub fn payment_required() -> Response

Start building a new Response with PAYMENT_REQUIRED as status code.

source

pub fn forbidden() -> Response

Start building a new Response with FORBIDDEN as status code.

source

pub fn method_not_allowed() -> Response

Start building a new Response with METHOD_NOT_ALLOWED as status code.

source

pub fn not_acceptable() -> Response

Start building a new Response with NOT_ACCEPTABLE as status code.

source

pub fn proxy_authentication_required() -> Response

Start building a new Response with PROXY_AUTHENTICATION_REQUIRED as status code.

source

pub fn request_timeout() -> Response

Start building a new Response with REQUEST_TIMEOUT as status code.

source

pub fn conflict() -> Response

Start building a new Response with CONFLICT as status code.

source

pub fn gone() -> Response

Start building a new Response with GONE as status code.

source

pub fn length_required() -> Response

Start building a new Response with LENGTH_REQUIRED as status code.

source

pub fn precondition_failed() -> Response

Start building a new Response with PRECONDITION_FAILED as status code.

source

pub fn precondition_required() -> Response

Start building a new Response with PRECONDITION_REQUIRED as status code.

source

pub fn payload_too_large() -> Response

Start building a new Response with PAYLOAD_TOO_LARGE as status code.

source

pub fn uri_too_long() -> Response

Start building a new Response with URI_TOO_LONG as status code.

source

pub fn unsupported_media_type() -> Response

Start building a new Response with UNSUPPORTED_MEDIA_TYPE as status code.

source

pub fn range_not_satisfiable() -> Response

Start building a new Response with RANGE_NOT_SATISFIABLE as status code.

source

pub fn expectation_failed() -> Response

Start building a new Response with EXPECTATION_FAILED as status code.

source

pub fn unprocessable_entity() -> Response

Start building a new Response with UNPROCESSABLE_ENTITY as status code.

source

pub fn too_many_requests() -> Response

Start building a new Response with TOO_MANY_REQUESTS as status code.

source

pub fn request_header_fields_too_large() -> Response

Start building a new Response with REQUEST_HEADER_FIELDS_TOO_LARGE as status code.

Start building a new Response with UNAVAILABLE_FOR_LEGAL_REASONS as status code.

source

pub fn internal_server_error() -> Response

Start building a new Response with INTERNAL_SERVER_ERROR as status code.

source

pub fn not_implemented() -> Response

Start building a new Response with NOT_IMPLEMENTED as status code.

source

pub fn bad_gateway() -> Response

Start building a new Response with BAD_GATEWAY as status code.

source

pub fn service_unavailable() -> Response

Start building a new Response with SERVICE_UNAVAILABLE as status code.

source

pub fn gateway_timeout() -> Response

Start building a new Response with GATEWAY_TIMEOUT as status code.

source

pub fn http_version_not_supported() -> Response

Start building a new Response with HTTP_VERSION_NOT_SUPPORTED as status code.

source

pub fn variant_also_negotiates() -> Response

Start building a new Response with VARIANT_ALSO_NEGOTIATES as status code.

source

pub fn insufficient_storage() -> Response

Start building a new Response with INSUFFICIENT_STORAGE as status code.

source

pub fn loop_detected() -> Response

Start building a new Response with LOOP_DETECTED as status code.

Trait Implementations§

source§

impl<Body> From<Response<Body>> for Response
where Body: Send + RawBody<Data = Bytes> + 'static, <Body as RawBody>::Error: Into<Box<dyn Error + Send + Sync>>,

source§

fn from(inner: Response<Body>) -> Self

Converts to this type from the input type.
source§

impl From<Response> for Response<ResponseBody>

source§

fn from(res: Response) -> Self

Converts to this type from the input type.
source§

impl IntoResponse for Response

source§

fn into_response(self) -> Response

Convert self into an HTTP response.

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