pub struct Response {
pub version: String,
pub status_code: StatusCode,
pub headers: Headers,
pub body: Vec<u8>,
}
Expand description
Represents a response from the server.
Implements Into<Vec<u8>>
so can be serialised into bytes to transmit.
Simple Creation
Response::new(StatusCode::OK, b"Success")
Advanced Creation
Response::empty(StatusCode::OK)
.with_bytes(b"Success")
.with_header(HeaderType::ContentType, "text/plain")
Fields§
§version: String
The HTTP version of the response.
status_code: StatusCode
The status code of the response, for example 200 OK.
headers: Headers
A list of the headers included in the response.
body: Vec<u8>
The body of the response.
Implementations§
source§impl Response
impl Response
sourcepub fn new<T>(status_code: StatusCode, bytes: T) -> Selfwhere
T: AsRef<[u8]>,
pub fn new<T>(status_code: StatusCode, bytes: T) -> Selfwhere T: AsRef<[u8]>,
Creates a new response object with the given status code, bytes and request. Functionally equivalent to the following (but with some allocation optimisations not shown):
Response::empty(status_code).with_bytes(bytes)
Note about Headers
If you want to add headers to a response, ideally use Response::empty
and the builder pattern
so as to not accidentally override important generated headers such as content length and connection.
sourcepub fn empty(status_code: StatusCode) -> Self
pub fn empty(status_code: StatusCode) -> Self
Creates a new response object with the given status code. Automatically sets the HTTP version to “HTTP/1.1”, sets no headers, and creates an empty body.
sourcepub fn redirect<T>(location: T) -> Selfwhere
T: AsRef<str>,
pub fn redirect<T>(location: T) -> Selfwhere T: AsRef<str>,
Creates a redirect response to the given location.
sourcepub fn with_header(
self,
header: impl HeaderLike,
value: impl AsRef<str>
) -> Self
pub fn with_header( self, header: impl HeaderLike, value: impl AsRef<str> ) -> Self
Adds the given header to the response. Returns itself for use in a builder pattern.
Adds the given cookie to the response in the Set-Cookie
header.
Returns itself for use in a builder pattern.
Example
Response::empty(StatusCode::OK)
.with_bytes(b"Success")
.with_cookie(
SetCookie::new("SessionToken", "abc123")
.with_max_age(Duration::from_secs(3600))
.with_secure(true)
.with_path("/")
)
sourcepub fn with_bytes<T>(self, bytes: T) -> Selfwhere
T: AsRef<[u8]>,
pub fn with_bytes<T>(self, bytes: T) -> Selfwhere T: AsRef<[u8]>,
Appends the given bytes to the body. Returns itself for use in a builder pattern.
sourcepub fn get_headers(&self) -> &Headers
pub fn get_headers(&self) -> &Headers
Returns a reference to the response’s headers.
sourcepub fn from_stream<T>(stream: &mut T) -> Result<Self, ResponseError>where
T: Read,
pub fn from_stream<T>(stream: &mut T) -> Result<Self, ResponseError>where T: Read,
Attempts to read and parse one HTTP response from the given stream.
Converts chunked transfer encoding into a regular body.