Skip to main content

Module header_from_str_config

Module header_from_str_config 

Expand description

Extract a header config from a request or response and insert it into Extensions.

§Example

use rama_http::layer::header_from_str_config::HeaderFromStrConfigLayer;
use rama_http::service::web::WebService;
use rama_http::{Body, Request, StatusCode, HeaderName};
use rama_core::{extensions::{Extension, ExtensionsRef}, Service, Layer};

#[derive(Debug, Clone, Extension)]
struct ProxyLabel(String);

impl std::str::FromStr for ProxyLabel {
    type Err = std::convert::Infallible;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(ProxyLabel(s.to_owned()))
    }
}

#[derive(Debug, Clone, Extension)]
struct ProxyLabels(Vec<ProxyLabel>);

impl FromIterator<ProxyLabel> for ProxyLabels {
    fn from_iter<I: IntoIterator<Item = ProxyLabel>>(iter: I) -> Self {
        Self(iter.into_iter().collect())
    }
}

#[tokio::main]
async fn main() {
    let service = HeaderFromStrConfigLayer::<ProxyLabel, ProxyLabels>::required(HeaderName::from_static("x-proxy-labels"))
        .with_repeat(true)
        .into_layer(WebService::default()
            .with_get("/", async |req: Request| {
                let labels: &ProxyLabels = req.extensions().get_ref().unwrap();
                assert_eq!("a+b+c", labels.0.iter().map(|l| l.0.as_str()).collect::<Vec<_>>().join("+"));
            }),
        );

    let request = Request::builder()
        .header("x-proxy-labels", "a, b")
        .header("x-proxy-labels", "c")
        .body(Body::empty())
        .unwrap();

    let resp = service.serve(request).await.unwrap();
    assert_eq!(resp.status(), StatusCode::OK);
}

Structs§

HeaderFromStrConfigLayer
Layer which extracts a header CSV config for the given HeaderName from a request or response and inserts it into the Extensions of that object.
HeaderFromStrConfigService
A Service which extracts a header CSV config from a request or response and inserts it into the Extensions of that object.