Skip to main content

Response

Struct Response 

Source
pub struct Response {
    pub http_version: String,
    pub status_code: i16,
    pub reason_phrase: String,
    pub headers: Vec<Header>,
    pub content_range_list: Vec<ContentRange>,
    pub stream_file: Option<String>,
    pub stream_pipe: Option<Box<dyn Read + Send>>,
    pub trailers: Option<Trailers>,
}
Expand description

An HTTP response. Build one inside [Controller::process] and return it.

Set status_code and reason_phrase from STATUS_CODE_REASON_PHRASE, push body content via Range::get_content_range into content_range_list, and add any extra headers to headers.

For large files, set stream_file to the absolute file path instead of loading the body into content_range_list. The server will stream it with Transfer-Encoding: chunked so memory usage stays constant regardless of file size.

For proxy passthrough (SSE, AI token streams, large downloads), set stream_pipe to a boxed Read source instead. The server streams its output with Transfer-Encoding: chunked immediately after sending the response headers.

Fields§

§http_version: String

HTTP version string, e.g. "HTTP/1.1".

§status_code: i16

Numeric status code, e.g. 200. Set from STATUS_CODE_REASON_PHRASE.

§reason_phrase: String

Reason phrase, e.g. "OK". Set from STATUS_CODE_REASON_PHRASE.

§headers: Vec<Header>

Response headers. Pre-populated with standard headers by Header::get_header_list.

§content_range_list: Vec<ContentRange>

Response body as a list of content ranges (supports multipart and range responses).

§stream_file: Option<String>

If set, the server streams this file with Transfer-Encoding: chunked instead of using content_range_list. Use for files larger than ~8 MB.

§stream_pipe: Option<Box<dyn Read + Send>>

If set, the server pipes bytes from this reader with Transfer-Encoding: chunked immediately after sending the response headers. Takes precedence over content_range_list and stream_file. The reader is consumed and not cloned.

§trailers: Option<Trailers>

Header fields sent after the body (HTTP/2 and HTTP/3; HTTP/1.1 drops them) — gRPC’s grpc-status and grpc-message. A streamed body’s producer fills the slot before it ends the stream. Since 18.3.0.

Implementations§

Source§

impl Response

Source

pub const _ERROR_UNABLE_TO_PARSE_HTTP_VERSION_STATUS_CODE: &'static str = "Unable to parse status code"

Source

pub const _HTTP_VERSION_AND_STATUS_CODE_AND_REASON_PHRASE_REGEX: &'static str = "(?P<http_version>\\w+/\\w+.\\w)\\s(?P<status_code>\\w+)\\s(?P<reason_phrase>.+)"

Source

pub fn with_status(status: &StatusCodeReasonPhrase) -> Response

A response with status, no headers and no body; set fields or push headers and body parts after.

use rust_web_server::response::{Response, STATUS_CODE_REASON_PHRASE};

let mut response = Response::with_status(STATUS_CODE_REASON_PHRASE.n204_no_content);
response.headers.push(rust_web_server::header::Header::new("X-Done", "yes"));
assert_eq!(response.status_code, 204);
Source

pub fn build( status: StatusCodeReasonPhrase, header_list: Vec<Header>, body: Vec<ContentRange>, ) -> Response

Source

pub fn status_code_reason_phrase_list() -> Vec<&'static StatusCodeReasonPhrase>

Source

pub fn _get_header(&self, name: String) -> Option<&Header>

Source

pub fn status_has_no_content(status_code: i16) -> bool

true for a status that never has content: 1xx, 204, 304 (RFC 9110 §6.4.1, §15.3.5, §15.4.5).

Source

pub fn drop_content_for_status(&mut self)

For a status without content (Response::status_has_no_content), drop the body — buffered, file or pipe — and any Content-Length or Transfer-Encoding, which those responses must not carry (#54). Every connection writer calls it before framing the response.

Source

pub fn generate_body(content_range_list: Vec<ContentRange>) -> Vec<u8> ⓘ

Source

pub fn generate_response(response: Response, request: Request) -> Vec<u8> ⓘ

The serialized response: status line + headers, then the body.

Source

pub fn generate_response_parts( response: Response, request: Request, ) -> (Vec<u8>, Vec<u8>)

Like generate_response, but returns the head (status line + headers + blank line) and the body separately, so a connection writer can send them back to back without first copying a large body into one combined buffer. The body is empty for HEAD and for a status without content.

Source

pub fn _parse_response(response_vec_u8: &[u8]) -> Response

Source

pub fn _parse_http_version_status_code_reason_phrase_string( http_version_status_code_reason_phrase: &str, ) -> Result<(String, i16, String), String>

Source

pub fn _parse_http_response_header_string(header_string: &str) -> Header

Source

pub fn _parse_raw_response_via_cursor( cursor: &mut Cursor<&[u8]>, iteration_number: usize, response: &mut Response, content_length: usize, )

Source

pub fn _is_multipart_byteranges_content_type(content_type: &Header) -> bool

Source

pub fn get_response( status_code_reason_phrase: &StatusCodeReasonPhrase, boxed_header_list: Option<Vec<Header>>, boxed_content_range_list: Option<Vec<ContentRange>>, ) -> Response

Source

pub fn json( status_code_reason_phrase: &StatusCodeReasonPhrase, body: Vec<u8>, ) -> Response

Build a Content-Type: application/json response from already-serialized bytes.

Takes raw bytes rather than a Serialize value so it carries no dependency on the serde feature — pair it with serde_json::to_vec (or hand-rolled JSON) to build body. For a one-line serialize-and-respond helper on a typed value, see crate::json::Json (serde feature).

use rust_web_server::response::{Response, STATUS_CODE_REASON_PHRASE};

let response = Response::json(STATUS_CODE_REASON_PHRASE.n200_ok, br#"{"ok":true}"#.to_vec());
Source

pub fn text( status_code_reason_phrase: &StatusCodeReasonPhrase, body: &str, ) -> Response

Build a Content-Type: text/plain response from a body string.

use rust_web_server::response::{Response, STATUS_CODE_REASON_PHRASE};

let response = Response::text(STATUS_CODE_REASON_PHRASE.n400_bad_request, "invalid input");
Source

pub fn generate(&mut self) -> Vec<u8> ⓘ

Source

pub fn get_header(&self, name: String) -> Option<&Header>

Source

pub fn header(&self, name: &str) -> Option<&Header>

The first header named name (case-insensitive), without allocating.

Source

pub fn parse(response_vec_u8: &[u8]) -> Result<Response, String>

Source

pub fn parse_raw_response_via_cursor( cursor: &mut Cursor<&[u8]>, iteration_number: usize, response: &mut Response, _content_length: usize, total_bytes: i32, bytes_read: i32, ) -> Result<(), String>

Source

pub fn parse_http_response_header_string( header_string: &str, ) -> Result<Header, String>

Trait Implementations§

Source§

impl Clone for Response

Source§

fn clone(&self) -> Response

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · 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<(), Error>

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

impl Default for Response

Source§

fn default() -> Response

The same as Response::new(): HTTP/1.1, no headers, no body, status 501 Not Implemented until you set one.

Source§

impl Eq for Response

Source§

impl IntoResponse for Response

Source§

impl New for Response

Source§

impl PartialEq for Response

Source§

fn eq(&self, other: &Response) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more

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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

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

Source§

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

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. 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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ServiceExt for T

Source§

fn map_response_body<F>(self, f: F) -> MapResponseBody<Self, F>
where Self: Sized,

Available on crate feature map-response-body only.
Apply a transformation to the response body. Read more
Source§

fn trace_for_http(self) -> Trace<Self, SharedClassifier<ServerErrorsAsFailures>>
where Self: Sized,

Available on crate feature trace only.
High level tracing that classifies responses using HTTP status codes. Read more
Source§

fn trace_for_grpc(self) -> Trace<Self, SharedClassifier<GrpcErrorsAsFailures>>
where Self: Sized,

Available on crate feature trace only.
High level tracing that classifies responses using gRPC headers. Read more
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 = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

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