liveBook · Manning

HTTP response

As explained in Rust Servers, Services, and Apps

HttpResponse is a Rust structure representing an HTTP response message with status information, headers, and an optional body.

`HttpResponse<'a>` represents an outgoing HTTP message in a Rust web server. A handler constructs the response; the HTTP library converts it to text that the server sends to the client over a TCP stream. The custom type lives in `http/src/httpresponse.rs` and is exported from `http/lib.rs`. section 2.3 section 2.3.2

The custom response has five fields:

  • `version`, `status_code`, and `status_text` describe the status line. `Default` sets them to `HTTP/1.1`, `200`, and `OK`. section 2.3.2
  • `headers` is an optional map of borrowed strings; `body` is an optional owned `String`. `new(status_code, headers, body)` supplies `Content-Type: text/html` when headers are omitted and selects status text for supported codes. section 2.3.2
  • A lifetime annotation ties borrowed field values to the lifetime of the response. Derived `Debug`, `PartialEq`, and `Clone` support inspection, comparison, and cloning. section 2.3.2
Listing 2.15 Code to serialize a Rust struct into an HTTP response message
impl<'a> From<HttpResponse<'a>> for String {
    fn from(res: HttpResponse) -> String {
        let res1 = res.clone();
        format!(
            "{} {} {}\r\n{}Content-Length: {}\r\n\r\n{}",
            &res1.version(),
            &res1.status_code(),
            &res1.status_text(),
            &res1.headers(),
            &res.body.unwrap().len(),
            &res1.body()
        )
    }
}

The `From<HttpResponse> for String` implementation assembles the status line, headers, `Content-Length`, blank line, and body using CRLF separators. It calls `unwrap()` on the body, so this serializer requires a body even though the field is optional. section 2.3.2

Return a missing-page response

`PageNotFoundHandler::handle` constructs `HttpResponse::new("404", None, Self::load_file("404.html"))`. The constructor supplies the default HTML content type and the `Not Found` status text. Tests compare constructed 200 and 404 responses and check the serialized 404 message; run them with `cargo test -p http`. section 2.3.4 section 2.3.2

Other handlers put static pages or JSON data in response bodies and choose a content type appropriate to the returned file. Keep this custom `http`-library type distinct from the `HttpResponse` used in Actix Web handlers: an Actix frontend also acts as a client when it reads a backend service’s JSON response body and deserializes it into `Vec<Tutor>`. section 2.3.4 section 7.7

How Rust Servers, Services, and Apps covers it

How deep it goes
Defines fields, defaults, constructor, string conversion, stream writing, and tests; also exposes a body-unwrapping limitation in the serializer.
Examples
Tests 200 and 404 construction and a serialized 404 message, then returns HTML pages and JSON data from handlers.
What it assumes
Assumes working familiarity with Rust structs and traits while explaining reference lifetimes and implementing response-related traits.
What you can do after
Build it from scratch as a Rust response type that handlers construct and serialize for HTTP clients.
How it connects
Links HTTP requests, routing, handlers, TCP streams, content types, and JSON responses.

Also explained in

Compare how 4 books explain HTTP response →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Rust Servers, Services, and Apps. The section links point to the parts of the book it draws on.