Crate tower_async_http
source ·Expand description
async fn(HttpRequest) -> Result<HttpResponse, Error>
Overview
tower-http is a library that provides HTTP-specific middleware and utilities built on top of tower-async.
All middleware uses the http and http-body crates as the HTTP abstractions. That means they’re compatible with any library or framework that also uses those crates, such as hyper, tonic, and warp.
Note that for these frameworks you do need to use the tower-async-bridge
crate to convert
between the tower-async
and tower
abstractions.
Example server
This example shows how to apply middleware from tower-http to a Service
and then run
that service using hyper.
use std::{sync::Arc, net::SocketAddr, convert::Infallible, iter::once};
use http::{Request, Response, StatusCode, header::{AUTHORIZATION, CONTENT_TYPE, HeaderName}};
use hyper::body::Incoming;
use hyper_util::rt::{TokioExecutor, TokioIo};
use hyper_util::server::conn::auto::Builder;
use tokio::net::TcpListener;
use tower_async::{ServiceBuilder, BoxError};
use tower_async_http::{
ServiceBuilderExt,
add_extension::AddExtensionLayer,
compression::CompressionLayer,
propagate_header::PropagateHeaderLayer,
sensitive_headers::SetSensitiveRequestHeadersLayer,
set_header::SetResponseHeaderLayer,
validate_request::ValidateRequestHeaderLayer,
};
use tower_async_hyper::{HyperBody, TowerHyperServiceExt};
// Our request handler. This is where we would implement the application logic
// for responding to HTTP requests...
async fn handler(request: Request<HyperBody>) -> Result<Response<HyperBody>, BoxError> {
// ...
}
// Shared state across all request handlers --- in this case, a pool of database connections.
struct State {
pool: DatabaseConnectionPool,
}
#[tokio::main]
async fn main() -> Result<(), BoxError> {
// Construct the shared state.
let state = State {
pool: DatabaseConnectionPool::new(),
};
// Use tower's `ServiceBuilder` API to build a stack of tower middleware
// wrapping our request handler.
let service = ServiceBuilder::new()
// To be able to use `Body` `Default` middleware
.map_request_body(HyperBody::from)
// Mark the `Authorization` request header as sensitive so it doesn't show in logs
.layer(SetSensitiveRequestHeadersLayer::new(once(AUTHORIZATION)))
// Share an `Arc<State>` with all requests
.layer(AddExtensionLayer::new(Arc::new(state)))
// Compress responses
.compression()
// Propagate `X-Request-Id`s from requests to responses
.layer(PropagateHeaderLayer::new(HeaderName::from_static("x-request-id")))
// If the response has a known size set the `Content-Length` header
.layer(SetResponseHeaderLayer::overriding(CONTENT_TYPE, content_length_from_response))
// Authorize requests using a token
.layer(ValidateRequestHeaderLayer::bearer("passwordlol"))
// Accept only application/json, application/* and */* in a request's ACCEPT header
.layer(ValidateRequestHeaderLayer::accept("application/json"))
// Wrap a `Service` in our middleware stack
.service_fn(handler);
let addr: SocketAddr = ([127, 0, 0, 1], 8080).into();
let listener = TcpListener::bind(addr).await?;
loop {
let (stream, _) = listener.accept().await?;
let service = service.clone().into_hyper_service();
tokio::spawn(async move {
let stream = TokioIo::new(stream);
let result = Builder::new(TokioExecutor::new())
.serve_connection(stream, service)
.await;
if let Err(e) = result {
eprintln!("server connection error: {}", e);
}
});
}
}
Keep in mind that while this example uses hyper, tower-http supports any HTTP client/server implementation that uses the http and http-body crates.
Example client
tower-http middleware can also be applied to HTTP clients:
use tower_async_http::{
decompression::DecompressionLayer,
set_header::SetRequestHeaderLayer,
};
use tower_async_bridge::AsyncServiceExt;
use tower_async::{ServiceBuilder, Service, ServiceExt};
use http_body_util::Full;
use bytes::Bytes;
use http::{Request, HeaderValue, header::USER_AGENT};
use hyper_util::{client::legacy::Client, rt::TokioExecutor};
#[tokio::main]
async fn main() {
let mut client = ServiceBuilder::new()
// Set a `User-Agent` header on all requests.
.layer(SetRequestHeaderLayer::overriding(
USER_AGENT,
HeaderValue::from_static("tower-http demo")
))
// Decompress response bodies
.layer(DecompressionLayer::new())
// Wrap a `hyper::Client` in our middleware stack.
// This is possible because `hyper::Client` implements
// `tower_async::Service`.
.service(Client::builder(TokioExecutor::new()).build_http().into_async());
// Make a request
let request = Request::builder()
.uri("http://example.com")
.body(Full::<Bytes>::default())
.unwrap();
let response = client
.call(request)
.await
.unwrap();
}
Feature Flags
All middleware are disabled by default and can be enabled using cargo features.
For example, to enable the Timeout
middleware, add the “timeout” feature flag in
your Cargo.toml
:
tower-async-http = { version = "0.2", features = ["timeout"] }
You can use "full"
to enable everything:
tower-async-http = { version = "0.2", features = ["full"] }
Modules
- add_extension
add-extension
Middleware that clones a value into each request’s extensions. - auth
auth
Authorization related middleware. - catch_panic
catch-panic
Convert panics into responses. - Tools for classifying responses as either success or failure.
- compression
compression-br
orcompression-deflate
orcompression-gzip
orcompression-zstd
Middleware that compresses response bodies. - cors
cors
Middleware which adds headers for CORS. - decompression
decompression-br
ordecompression-deflate
ordecompression-gzip
ordecompression-zstd
Middleware that decompresses request and response bodies. - follow_redirect
follow-redirect
Middleware for following redirections. - limit
limit
Middleware for limiting request bodies. - map_request_body
map-request-body
Apply a transformation to the request body. - map_response_body
map-response-body
Apply a transformation to the response body. - normalize_path
normalize-path
Middleware that normalizes paths. - propagate_header
propagate-header
Propagate a header from the request to the response. - request_id
request-id
Set and propagate request ids. - sensitive_headers
sensitive-headers
Middlewares that mark headers as sensitive. - set_header
set-header
Middleware for setting headers on requests and responses. - set_status
set-status
Middleware to override status codes. - timeout
timeout
Middleware that applies a timeout to requests. - trace
trace
- validate_request
validate-request
Middleware that validates requests.
Enums
- CompressionLevel
compression-br
orcompression-deflate
orcompression-gzip
orcompression-zstd
ordecompression-br
ordecompression-deflate
ordecompression-gzip
ordecompression-zstd
Level of compression data should be compressed with. - The latency unit used to report latencies by middleware.
Traits
- Extension trait that adds methods to
tower_async::ServiceBuilder
for adding middleware from tower-http.
Type Aliases
- Alias for a type-erased error type.