pub struct App<S> { /* private fields */ }Expand description
An HTTP server application with typed state, routing, and TLS support.
App<S> serves requests by routing them to handlers based on method and path.
All handlers share access to a single S value (the app state), cloned as an Arc
per request for zero-allocation sharing.
§Example
use mini_serve::App;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let app = App::new(());
app.bind("127.0.0.1:8080".parse()?).await?;
Ok(())
}§Features
- Routing: Register handlers for (Method, Path) pairs with path parameters (
/users/:id). - State sharing: All handlers receive
Arc<S>to the app state. - Request extraction: Parse bodies, extract path/query params, and build responses.
- CORS: Optional cross-origin request handling with preflight validation.
- TLS: Serve over HTTPS when the
tlsfeature is enabled. - Graceful shutdown: Drain in-flight requests before exiting.
Implementations§
Source§impl<S: Send + Sync + 'static> App<S>
impl<S: Send + Sync + 'static> App<S>
Sourcepub fn new(state: S) -> Self
pub fn new(state: S) -> Self
Create a new app with shared state.
The state is wrapped in an Arc and shared with every request handler
as State::from_arc(). Route registration is done via RouteBuilder.
Sourcepub fn state_arc(&self) -> Arc<S> ⓘ
pub fn state_arc(&self) -> Arc<S> ⓘ
Get an Arc to the app state.
Useful for spawning background tasks or accessing state outside the request-response loop.
pub async fn route(&self, req: Request<Incoming>) -> Response<ResponseBody>
Sourcepub async fn bind_ephemeral(self) -> Result<u16, ServeError>
pub async fn bind_ephemeral(self) -> Result<u16, ServeError>
Bind to an ephemeral port and serve in the background.
Returns the assigned port number. The server runs in a spawned task
and serves until the process exits. For graceful shutdown, use run().
Binds to 127.0.0.1 only—safe for development and testing.
Sourcepub async fn run<F>(
self,
listener: TcpListener,
shutdown: F,
) -> Result<(), ServeError>
pub async fn run<F>( self, listener: TcpListener, shutdown: F, ) -> Result<(), ServeError>
Serve listener until shutdown resolves, then drain in-flight
connections and return. The production entry point for callers that
want control over the shutdown trigger (tests, custom signals); see
App::bind for the OS-signal convenience wrapper.
Sourcepub async fn bind(self, addr: SocketAddr) -> Result<(), ServeError>
pub async fn bind(self, addr: SocketAddr) -> Result<(), ServeError>
Bind addr and serve until SIGINT or SIGTERM, then drain in-flight
connections and return. Unlike App::bind_ephemeral, addr is
caller-chosen — e.g. 0.0.0.0:$PORT for a platform like fly.io that
routes external traffic to the process directly.