http

Module response

Source
Expand description

HTTP response types.

This module contains structs related to HTTP responses, notably the Response type itself as well as a builder to create responses. Typically you’ll import the http::Response type rather than reaching into this module itself.

§Examples

Creating a Response to return

use http::{Request, Response, StatusCode};

fn respond_to(req: Request<()>) -> http::Result<Response<()>> {
    let mut builder = Response::builder()
        .header("Foo", "Bar")
        .status(StatusCode::OK);

    if req.headers().contains_key("Another-Header") {
        builder = builder.header("Another-Header", "Ack");
    }

    builder.body(())
}

A simple 404 handler

use http::{Request, Response, StatusCode};

fn not_found(_req: Request<()>) -> http::Result<Response<()>> {
    Response::builder()
        .status(StatusCode::NOT_FOUND)
        .body(())
}

Or otherwise inspecting the result of a request:

use http::{Request, Response};

fn get(url: &str) -> http::Result<Response<()>> {
    // ...
}

let response = get("https://www.rust-lang.org/").unwrap();

if !response.status().is_success() {
    panic!("failed to get a successful response status!");
}

if let Some(date) = response.headers().get("Date") {
    // we've got a `Date` header!
}

let body = response.body();
// ...

Structs§

  • An HTTP response builder
  • Component parts of an HTTP Response
  • Represents an HTTP response