Module rama::http::layer::set_header::response

Expand description

Set a header on the response.

The header value to be set may be provided as a fixed value when the middleware is constructed, or determined dynamically based on the response by a closure. See the MakeHeaderValue trait for details.

§Example

Setting a header from a fixed value provided when the middleware is constructed:

use rama_http::layer::set_header::SetResponseHeaderLayer;
use rama_http::{Body, Request, Response, header::{self, HeaderValue}};
use rama_core::service::service_fn;
use rama_core::{Context, Service, Layer};
use rama_core::error::BoxError;

let mut svc = (
    // Layer that sets `Content-Type: text/html` on responses.
    //
    // `if_not_present` will only insert the header if it does not already
    // have a value.
    SetResponseHeaderLayer::if_not_present(
        header::CONTENT_TYPE,
        HeaderValue::from_static("text/html"),
    ),
).layer(render_html);

let request = Request::new(Body::empty());

let response = svc.serve(Context::default(), request).await?;

assert_eq!(response.headers()["content-type"], "text/html");

Setting a header based on a value determined dynamically from the response:

use rama_http::layer::set_header::SetResponseHeaderLayer;
use rama_http::{Body, Request, Response, header::{self, HeaderValue}};
use crate::rama_http::dep::http_body::Body as _;
use rama_core::service::service_fn;
use rama_core::{Context, Service, Layer};
use rama_core::error::BoxError;

let mut svc = (
    // Layer that sets `Content-Length` if the body has a known size.
    // Bodies with streaming responses wont have a known size.
    //
    // `overriding` will insert the header and override any previous values it
    // may have.
    SetResponseHeaderLayer::overriding_fn(
        header::CONTENT_LENGTH,
        |response: Response| async move {
            let value = if let Some(size) = response.body().size_hint().exact() {
                // If the response body has a known size, returning `Some` will
                // set the `Content-Length` header to that value.
                Some(HeaderValue::from_str(&size.to_string()).unwrap())
            } else {
                // If the response body doesn't have a known size, return `None`
                // to skip setting the header on this response.
                None
            };
            (response, value)
        }
    ),
).layer(render_html);

let request = Request::new(Body::empty());

let response = svc.serve(Context::default(), request).await?;

assert_eq!(response.headers()["content-length"], "10");

Structs§