pub struct Server { /* private fields */ }Expand description
The HTTP server that owns and dispatches a collection of SocketType routes.
Build routes through the ServerMechanism builder chain, register each with
mechanism, then start the server with serve.
§Example
let mut server = Server::default();
server
.mechanism(
ServerMechanism::get("/ping")
.onconnect(|| async { reply!(json => Pong { ok: true }) })
)
.mechanism(
ServerMechanism::delete("/session")
.onconnect(|| async { reply!(message => warp::reply(), status => Status::NoContent) })
);
// Blocks forever — call only to actually run the server:
// server.serve(([0, 0, 0, 0], 8080)).await;§Caution
Calling serve with no routes registered will panic.
Implementations§
Source§impl Server
impl Server
Sourcepub fn mechanism(&mut self, mech: SocketType) -> &mut Self
pub fn mechanism(&mut self, mech: SocketType) -> &mut Self
Registers a SocketType route on this server.
Routes are evaluated in registration order. Returns &mut Self for method chaining.
Sourcepub async fn serve(self, addr: impl Into<SocketAddr>)
pub async fn serve(self, addr: impl Into<SocketAddr>)
Sourcepub async fn serve_with_graceful_shutdown(
self,
addr: impl Into<SocketAddr>,
shutdown: impl Future<Output = ()> + Send + 'static,
)
pub async fn serve_with_graceful_shutdown( self, addr: impl Into<SocketAddr>, shutdown: impl Future<Output = ()> + Send + 'static, )
Binds to addr, serves all registered routes, and shuts down gracefully when
shutdown resolves.
Equivalent to calling serve_from_listener with an
address instead of a pre-bound listener.
§Example
use tokio::sync::oneshot;
let (tx, rx) = oneshot::channel::<()>();
// ... build server and mount routes ...
// trigger shutdown later by calling tx.send(())
server.serve_with_graceful_shutdown(([127, 0, 0, 1], 8080), async move {
rx.await.ok();
}).await;Sourcepub async fn serve_from_listener(
self,
listener: TcpListener,
shutdown: impl Future<Output = ()> + Send + 'static,
)
pub async fn serve_from_listener( self, listener: TcpListener, shutdown: impl Future<Output = ()> + Send + 'static, )
Serves all registered routes from an already-bound listener, shutting down gracefully
when shutdown resolves.
Use this when port 0 is passed to TcpListener::bind and you need to know the actual
OS-assigned port before the server starts (e.g. to open a browser to the correct URL).
§Example
use tokio::net::TcpListener;
use tokio::sync::oneshot;
let listener = TcpListener::bind("127.0.0.1:0").await?;
let port = listener.local_addr()?.port();
println!("Will listen on port {port}");
let (tx, rx) = oneshot::channel::<()>();
// ... build server and mount routes ...
server.serve_from_listener(listener, async move { rx.await.ok(); }).await;