Module tower_http::set_header::response [−][src]
This is supported on crate feature
set-header
only.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 http::{Request, Response, header::{self, HeaderValue}}; use tower::{Service, ServiceExt, ServiceBuilder}; use tower_http::set_header::SetResponseHeaderLayer; use hyper::Body; let mut svc = ServiceBuilder::new() .layer( // Layer that sets `Content-Type: text/html` on responses. // // We have to add `::<_, Body>` since Rust cannot infer the body type when // we don't use a closure to produce the header value. // // `if_not_present` will only insert the header if it does not already // have a value. SetResponseHeaderLayer::<_, Body>::if_not_present( header::CONTENT_TYPE, HeaderValue::from_static("text/html"), ) ) .service(render_html); let request = Request::new(Body::empty()); let response = svc.ready().await?.call(request).await?; assert_eq!(response.headers()["content-type"], "text/html");
Setting a header based on a value determined dynamically from the response:
use http::{Request, Response, header::{self, HeaderValue}}; use tower::{Service, ServiceExt, ServiceBuilder}; use tower_http::set_header::SetResponseHeaderLayer; use hyper::Body; use http_body::Body as _; // for `Body::size_hint` let mut svc = ServiceBuilder::new() .layer( // 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( header::CONTENT_LENGTH, |response: &Response<Body>| { 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 } } ) ) .service(render_html); let request = Request::new(Body::empty()); let response = svc.ready().await?.call(request).await?; assert_eq!(response.headers()["content-length"], "10");
Structs
ResponseFuture | Response future for |
SetResponseHeader | Middleware that sets a header on the response. |
SetResponseHeaderLayer | Layer that applies |