pub struct App { /* private fields */ }Expand description
An HTTP application: routes, state, middleware, lifespan and metadata.
Implementations§
Source§impl App
impl App
Sourcepub fn description(self, description: impl Into<String>) -> Self
pub fn description(self, description: impl Into<String>) -> Self
Set the API description.
Sourcepub fn docs(self, docs: DocsConfig) -> Self
pub fn docs(self, docs: DocsConfig) -> Self
Configure documentation endpoints.
Sourcepub fn route(self, path: &str, methods: MethodRouter) -> Self
pub fn route(self, path: &str, methods: MethodRouter) -> Self
Register methods at path (use {param} for path parameters).
Sourcepub fn routes(self, routes: impl IntoIterator<Item = Route>) -> Self
pub fn routes(self, routes: impl IntoIterator<Item = Route>) -> Self
Register routes produced by route macros (see routes![]).
Sourcepub fn mount(self, prefix: &str, app: App) -> Self
pub fn mount(self, prefix: &str, app: App) -> Self
Mount app under prefix (e.g. /api/v1); / merges its routes
into this app. See the module docs.
Sourcepub fn nest(self, prefix: &str, app: App) -> Self
pub fn nest(self, prefix: &str, app: App) -> Self
Alias of App::mount.
Sourcepub fn with_state<T: Send + Sync + 'static>(self, state: T) -> Self
pub fn with_state<T: Send + Sync + 'static>(self, state: T) -> Self
Make state available to handlers through State<T>.
Applies to every route of this app regardless of call order.
Sourcepub fn database(self, alias: impl Into<String>, db: Db) -> Self
pub fn database(self, alias: impl Into<String>, db: Db) -> Self
Register db under alias ("default", "replica", …).
Every registered database is available to handlers as
State<Databases>; a router set with App::databases is kept.
Sourcepub fn databases(self, databases: Databases) -> Self
pub fn databases(self, databases: Databases) -> Self
Replace the whole database registry (aliases and router).
Sourcepub fn database_registry(&self) -> Option<&Databases>
pub fn database_registry(&self) -> Option<&Databases>
The registered databases, if any.
Sourcepub fn openapi(&self) -> Result<OpenApi, OpenApiError>
pub fn openapi(&self) -> Result<OpenApi, OpenApiError>
Generate the OpenAPI 3.1 document for this app and its mounts.
§Errors
Returns OpenApiError on duplicate operations/ids or schema name
conflicts.
Sourcepub fn into_router_service(self) -> Result<RouterService, ServerError>
pub fn into_router_service(self) -> Result<RouterService, ServerError>
Convert into an in-process tower::Service (used by the testkit).
Lifespan hooks are not run.
§Errors
Returns ServerError::Configuration if the app is misconfigured.
Sourcepub fn into_service_with_lifespan(
self,
) -> Result<(RouterService, Lifespan), ServerError>
pub fn into_service_with_lifespan( self, ) -> Result<(RouterService, Lifespan), ServerError>
Like App::into_router_service, but also returns the Lifespan
so the caller can run startup and shutdown hooks around the service
without binding a socket (used by the testkit).
§Errors
Returns ServerError::Configuration if the app is misconfigured.
Sourcepub async fn run(self, addr: &str) -> Result<(), ServerError>
pub async fn run(self, addr: &str) -> Result<(), ServerError>
Serve until Ctrl-C or Unix SIGTERM, then drain and clean up resources.
Args: addr: Address to bind.
Returns: Success after shutdown and resource cleanup.
§Errors
Configuration, startup, bind, serving or shutdown errors.
Sourcepub async fn run_until<F>(
self,
addr: &str,
shutdown: F,
) -> Result<(), ServerError>
pub async fn run_until<F>( self, addr: &str, shutdown: F, ) -> Result<(), ServerError>
Serve until a caller-supplied shutdown future completes.
Startup cancellation and bind failure clean initialized resources. HTTP draining and teardown share one deadline. Connection, stream and WebSocket workers are cancelled before resource teardown.
Args: addr: Address to bind. shutdown: Future requesting graceful termination.
Returns: Success after serving and cleanup finish.
§Errors
Configuration/startup/I/O errors or exceeded shutdown deadline.
Source§impl App
impl App
Sourcepub fn background_tasks(self, limits: BackgroundTaskLimits) -> Self
pub fn background_tasks(self, limits: BackgroundTaskLimits) -> Self
Configure admission and execution limits for this app’s task queue.
Args: limits: Positive limits within Tokio semaphore capacity.
Returns: Configured app; invalid limits become a configuration error.
Source§impl App
impl App
Sourcepub fn provide<T: Send + Sync + 'static>(self, value: T) -> Self
pub fn provide<T: Send + Sync + 'static>(self, value: T) -> Self
Share value with every request of this app (and its mounts). See the
module docs.
Sourcepub fn provide_arc<T: Send + Sync + 'static>(self, value: Arc<T>) -> Self
pub fn provide_arc<T: Send + Sync + 'static>(self, value: Arc<T>) -> Self
Like App::provide for a value that is already shared, so the
caller can keep a handle to it.
Sourcepub fn override_dependency<T, F, Fut>(self, f: F) -> Selfwhere
T: Dependency,
F: Fn(RequestHead) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<T, ApiError>> + Send + 'static,
pub fn override_dependency<T, F, Fut>(self, f: F) -> Selfwhere
T: Dependency,
F: Fn(RequestHead) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<T, ApiError>> + Send + 'static,
Replace T::resolve with f (also for nested resolution). f gets an
owned RequestHead because a borrowed request cannot cross the
returned future.
Sourcepub fn override_value<T: Dependency + Clone>(self, value: T) -> Self
pub fn override_value<T: Dependency + Clone>(self, value: T) -> Self
Replace T::resolve with a clone of value.
Sourcepub fn dependency<T: Dependency>(self) -> Self
pub fn dependency<T: Dependency>(self) -> Self
Resolve T before every routed request; its error short-circuits.
The value stays cached, so handlers asking for Depends<T> reuse it.
Source§impl App
impl App
Sourcepub fn shutdown_timeout(self, budget: Duration) -> Self
pub fn shutdown_timeout(self, budget: Duration) -> Self
Set the total graceful-shutdown budget, including resource teardown.
Args: budget: Positive, representable duration (default: 30 seconds).
Returns: The configured application; invalid budgets fail validation.
Sourcepub fn on_startup<F, Fut>(self, hook: F) -> Self
pub fn on_startup<F, Fut>(self, hook: F) -> Self
Run hook at startup (before the socket is bound).
Sourcepub fn on_shutdown<F, Fut>(self, hook: F) -> Self
pub fn on_shutdown<F, Fut>(self, hook: F) -> Self
Run hook at shutdown (hooks run in reverse registration order).
Sourcepub fn lifespan_resource<T, F, Fut, C>(self, init: F) -> Self
pub fn lifespan_resource<T, F, Fut, C>(self, init: F) -> Self
Create a resource at startup and tear it down at shutdown.
init returns the value and a teardown future (which may capture
clones of whatever it needs to close). Handlers receive the value via
Resource<T>. Resources are torn down in reverse registration order.
Source§impl App
impl App
Sourcepub fn layer<L>(self, layer: L) -> Self
pub fn layer<L>(self, layer: L) -> Self
Wrap the application in layer. See the module docs for the
ordering rules.
Sourcepub fn compression(self, compression: Compression) -> Self
pub fn compression(self, compression: Compression) -> Self
Add Compression middleware.
Sourcepub fn csrf_origin(self, csrf: CsrfOrigin) -> Self
pub fn csrf_origin(self, csrf: CsrfOrigin) -> Self
Add CsrfOrigin middleware.
Sourcepub fn trusted_hosts(self, hosts: TrustedHosts) -> Self
pub fn trusted_hosts(self, hosts: TrustedHosts) -> Self
Add TrustedHosts middleware.
Sourcepub fn https_redirect(self, redirect: HttpsRedirect) -> Self
pub fn https_redirect(self, redirect: HttpsRedirect) -> Self
Add HttpsRedirect middleware.
Sourcepub fn request_id(self) -> Self
pub fn request_id(self) -> Self
Add request-id middleware with default settings.
Sourcepub fn request_logging(self) -> Self
pub fn request_logging(self) -> Self
Add RequestLogging middleware.
Sourcepub fn concurrency_limit(self, max: usize) -> Self
pub fn concurrency_limit(self, max: usize) -> Self
Add a ConcurrencyLimit.
Sourcepub fn body_limit(self, max_bytes: usize) -> Self
pub fn body_limit(self, max_bytes: usize) -> Self
Add a BodyLimit of max_bytes.
Sourcepub fn rate_limit(self, limit: RateLimit) -> Self
pub fn rate_limit(self, limit: RateLimit) -> Self
Add a RateLimit.
Source§impl App
impl App
Sourcepub fn server_limits(self, limits: ServerLimits) -> Self
pub fn server_limits(self, limits: ServerLimits) -> Self
Configure bounded transport admission before binding the server.
Args: limits: Accepted socket and per-connection HTTP/2 limits.
Returns: This application; invalid bounds become configuration errors.
Source§impl App
impl App
Sourcepub fn static_files(self, prefix: &str, dir: impl Into<PathBuf>) -> Self
pub fn static_files(self, prefix: &str, dir: impl Into<PathBuf>) -> Self
Serve files from dir under URL prefix (for example /assets).
The mount is not documented in OpenAPI. Path traversal (.. segments)
is rejected by tower-http’s ServeDir. A root prefix (/ or empty)
serves dir as the fallback for every path no route matches.
Sourcepub fn spa(self, prefix: &str, dir: impl Into<PathBuf>) -> Self
pub fn spa(self, prefix: &str, dir: impl Into<PathBuf>) -> Self
Serve a single-page application from dir under prefix (/
for the whole site): files as they are, and dir/index.html for
browser navigations to any other path below prefix, so client
side routes (/app/settings) load the app.
Explicit routes still win. The fallback applies only to GET and
HEAD requests accepting text/html whose last path segment has
no extension; a missing asset, an API-style request or a missing
index.html answer with the 404 problem document, and other
methods with 405. Paths are resolved inside the canonical dir
(no .., encoded or not, and no symbolic link leading out). The
mount is not documented in OpenAPI.
Trait Implementations§
Auto Trait Implementations§
impl !RefUnwindSafe for App
impl !Sync for App
impl !UnwindSafe for App
impl Freeze for App
impl Send for App
impl Unpin for App
impl UnsafeUnpin for App
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
§impl<T> Instrument for T
impl<T> Instrument for T
§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
impl<T> Read<Exclusive, BecauseExclusive> for Twhere
T: ?Sized,
§impl<T> ServiceExt for T
impl<T> ServiceExt for T
§fn compression(self) -> Compression<Self>where
Self: Sized,
fn compression(self) -> Compression<Self>where
Self: Sized,
§fn trace_for_http(self) -> Trace<Self, SharedClassifier<ServerErrorsAsFailures>>where
Self: Sized,
fn trace_for_http(self) -> Trace<Self, SharedClassifier<ServerErrorsAsFailures>>where
Self: Sized,
§fn trace_for_grpc(self) -> Trace<Self, SharedClassifier<GrpcErrorsAsFailures>>where
Self: Sized,
fn trace_for_grpc(self) -> Trace<Self, SharedClassifier<GrpcErrorsAsFailures>>where
Self: Sized,
§fn override_request_header<M>(
self,
header_name: HeaderName,
make: M,
) -> SetRequestHeader<Self, M>where
Self: Sized,
fn override_request_header<M>(
self,
header_name: HeaderName,
make: M,
) -> SetRequestHeader<Self, M>where
Self: Sized,
§fn append_request_header<M>(
self,
header_name: HeaderName,
make: M,
) -> SetRequestHeader<Self, M>where
Self: Sized,
fn append_request_header<M>(
self,
header_name: HeaderName,
make: M,
) -> SetRequestHeader<Self, M>where
Self: Sized,
§fn insert_request_header_if_not_present<M>(
self,
header_name: HeaderName,
make: M,
) -> SetRequestHeader<Self, M>where
Self: Sized,
fn insert_request_header_if_not_present<M>(
self,
header_name: HeaderName,
make: M,
) -> SetRequestHeader<Self, M>where
Self: Sized,
§fn override_response_header<M>(
self,
header_name: HeaderName,
make: M,
) -> SetResponseHeader<Self, M>where
Self: Sized,
fn override_response_header<M>(
self,
header_name: HeaderName,
make: M,
) -> SetResponseHeader<Self, M>where
Self: Sized,
§fn append_response_header<M>(
self,
header_name: HeaderName,
make: M,
) -> SetResponseHeader<Self, M>where
Self: Sized,
fn append_response_header<M>(
self,
header_name: HeaderName,
make: M,
) -> SetResponseHeader<Self, M>where
Self: Sized,
§fn insert_response_header_if_not_present<M>(
self,
header_name: HeaderName,
make: M,
) -> SetResponseHeader<Self, M>where
Self: Sized,
fn insert_response_header_if_not_present<M>(
self,
header_name: HeaderName,
make: M,
) -> SetResponseHeader<Self, M>where
Self: Sized,
§fn set_request_id<M>(
self,
header_name: HeaderName,
make_request_id: M,
) -> SetRequestId<Self, M>where
Self: Sized,
M: MakeRequestId,
fn set_request_id<M>(
self,
header_name: HeaderName,
make_request_id: M,
) -> SetRequestId<Self, M>where
Self: Sized,
M: MakeRequestId,
§fn set_x_request_id<M>(self, make_request_id: M) -> SetRequestId<Self, M>where
Self: Sized,
M: MakeRequestId,
fn set_x_request_id<M>(self, make_request_id: M) -> SetRequestId<Self, M>where
Self: Sized,
M: MakeRequestId,
x-request-id as the header name. Read more§fn propagate_request_id(
self,
header_name: HeaderName,
) -> PropagateRequestId<Self>where
Self: Sized,
fn propagate_request_id(
self,
header_name: HeaderName,
) -> PropagateRequestId<Self>where
Self: Sized,
§fn propagate_x_request_id(self) -> PropagateRequestId<Self>where
Self: Sized,
fn propagate_x_request_id(self) -> PropagateRequestId<Self>where
Self: Sized,
x-request-id as the header name. Read more§fn request_body_limit(self, limit: usize) -> RequestBodyLimit<Self>where
Self: Sized,
fn request_body_limit(self, limit: usize) -> RequestBodyLimit<Self>where
Self: Sized,
413 Payload Too Large responses. Read more