Module tower_http::set_header::request
source · Available on crate feature
set-header
only.Expand description
Set a header on the request.
The header value to be set may be provided as a fixed value when the
middleware is constructed, or determined dynamically based on the request
by a closure. See the MakeHeaderValue
trait for details.
Example
Setting a header from a fixed value provided when the middleware is constructed:
use http::{Request, Response, header::{self, HeaderValue}};
use tower::{Service, ServiceExt, ServiceBuilder};
use tower_http::set_header::SetRequestHeaderLayer;
use hyper::Body;
let mut svc = ServiceBuilder::new()
.layer(
// Layer that sets `User-Agent: my very cool app` on requests.
//
// `if_not_present` will only insert the header if it does not already
// have a value.
SetRequestHeaderLayer::if_not_present(
header::USER_AGENT,
HeaderValue::from_static("my very cool app"),
)
)
.service(http_client);
let request = Request::new(Body::empty());
let response = svc.ready().await?.call(request).await?;
Setting a header based on a value determined dynamically from the request:
use http::{Request, Response, header::{self, HeaderValue}};
use tower::{Service, ServiceExt, ServiceBuilder};
use tower_http::set_header::SetRequestHeaderLayer;
use hyper::Body;
fn date_header_value() -> HeaderValue {
// ...
}
let mut svc = ServiceBuilder::new()
.layer(
// Layer that sets `Date` to the current date and time.
//
// `overriding` will insert the header and override any previous values it
// may have.
SetRequestHeaderLayer::overriding(
header::DATE,
|request: &Request<Body>| {
Some(date_header_value())
}
)
)
.service(http_client);
let request = Request::new(Body::empty());
let response = svc.ready().await?.call(request).await?;
Structs
- Middleware that sets a header on the request.
- Layer that applies
SetRequestHeader
which adds a request header.