Skip to main content

Response

Struct Response 

Source
pub struct Response {
    pub status: u16,
    pub body: Body,
    pub content_type: &'static str,
    pub headers: Headers,
}
Expand description

An HTTP response to be sent to the client.

Construct responses using the factory methods (Response::text, Response::json, Response::file, etc.) and customise with Response::with_header and status code assignment.

§Examples

// Plain text
Response::text("Hello, world!")

// JSON (Schema-JIT serialization)
Response::json(&user)

// Custom status + headers
let mut res = Response::json(&item);
res.status = 201;
res.with_header("Location", "/items/42")

Fields§

§status: u16§body: Body§content_type: &'static str§headers: Headers

Custom response headers — stored inline (stack) for ≤8 headers, falling back to heap for more. No allocation for common cases.

Implementations§

Source§

impl Response

Source

pub fn new(status: u16) -> Self

Create a response with no body and a given status code.

Source

pub fn with_header( self, name: &'static str, value: impl IntoHeaderValue, ) -> Self

Builder-style method to append an HTTP response header.

The value may be a &'static str, String, or any integer type. Short values (≤ 64 bytes) are stored inline on the stack; longer values fall back to heap allocation.

Source

pub fn text(body: impl Into<Vec<u8>>) -> Self

200 OK with a plain-text body.

Source

pub fn text_static(body: &'static [u8]) -> Self

200 OK with a zero-copy static plain-text body. Avoids heap allocation — ideal for fixed responses like TFB plaintext.

Source

pub fn json_bytes(body: impl Into<Vec<u8>>) -> Self

200 OK with a pre-serialized JSON byte body. Use Response::json() when you have a typed value to serialize.

Source

pub fn json<T: Serialize>(val: &T) -> Self

200 OK — serializes a typed value to JSON using the Schema-JIT engine. This is the primary way to return structured data from a handler.

Source

pub fn json_static(body: &'static [u8]) -> Self

200 OK with a zero-copy static pre-serialized JSON body.

The fastest JSON response: &'static [u8] known at compile time. Zero heap allocation on every request.

§Example
// Pre-bake at compile time:
Response::json_static(b"{\"message\":\"Hello, World!\"}")
Source

pub fn raw(bytes: &'static [u8]) -> Self

Emit a fully pre-baked HTTP/1.1 response verbatim.

The supplied bytes must be a complete, valid HTTP/1.1 response (status line + headers + blank line + body). The worker writes them as-is, bypassing every header serialization step.

This is the absolute fastest response path — a single memcpy into the connection’s write_buf, then one write(2) syscall.

§Safety contract

You must include Date:, Content-Length:, and Content-Type: headers yourself. Chopin will NOT add them for Body::Raw responses.

§Example
// Build once at program start:
static PONG: &[u8] = b"HTTP/1.1 200 OK\r\n\
    Server: chopin\r\n\
    Content-Type: text/plain\r\n\
    Content-Length: 4\r\n\
    Connection: keep-alive\r\n\
    \r\n\
    pong";

fn pong(_ctx: Context) -> Response { Response::raw(PONG) }
Source

pub fn not_found() -> Self

404 Not Found.

Source

pub fn server_error() -> Self

500 Internal Server Error.

Source

pub fn bad_request() -> Self

400 Bad Request.

Source

pub fn unauthorized() -> Self

401 Unauthorized.

Source

pub fn forbidden() -> Self

403 Forbidden.

Source

pub fn stream(iter: impl Iterator<Item = Vec<u8>> + Send + 'static) -> Self

Chunked streaming response with application/octet-stream content type.

Source

pub fn file(path: &str) -> Self

Serve a file using zero-copy sendfile. Content-Type is inferred from the file extension. Returns 404 if the file does not exist or cannot be opened.

Source

pub fn sendfile( fd: i32, offset: u64, len: u64, content_type: &'static str, ) -> Self

Serve a byte range of a file (e.g. for Range header support). The caller provides an already-opened fd, offset, and length. Ownership of the fd is transferred to the response.

Trait Implementations§

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.

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