Module header_from_str_config
Available on crate features
http and std only.Expand description
Extract a header config from a request or response and insert it into Extensions.
By default a single T is parsed from the header. Use Repeated as the mode
to parse all comma-separated values of all matching headers into a container C.
§Example
use rama_http::layer::header_from_str_config::{HeaderFromStrConfigLayer, Repeated};
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, Repeated<ProxyLabels>>::required(HeaderName::from_static("x-proxy-labels"))
.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§
- Header
From StrConfig Layer - Layer which extracts a header config for the given HeaderName
from a request or response and inserts it into the
Extensionsof that object. - Header
From StrConfig Service - A
Servicewhich extracts a header config from a request or response and inserts it into theExtensionsof that object. - Repeated
- Mode in which all comma-separated values of all matching headers
are parsed as
Tand inserted collected into a containerC. - Single
- Mode in which a single
Tis parsed from the header and inserted as-is.