Skip to main content

Server

Struct Server 

Source
pub struct Server<A: ApiSpec> { /* private fields */ }
Expand description

A type-safe HTTP server parameterized by an API specification.

The A type parameter is the API type — a tuple of endpoints. The server ensures at compile time (via Serves) that every endpoint has a handler.

§Example

type API = (
    GetEndpoint<path!("hello"), String>,
);

let server = Server::<API>::new((hello_handler,));
server.serve("127.0.0.1:3000".parse().unwrap()).await?;

Implementations§

Source§

impl<A: ApiSpec> Server<A>

Source

pub fn new<H: Serves<A>>(handlers: H) -> Self

Create a new server with handlers covering the full API.

Fails to compile if the handler tuple doesn’t match the API type.

Source

pub fn nest(self, prefix: &str) -> Self

Set a path prefix for all routes in this server.

Only requests whose path starts with the prefix will match. The prefix is stripped before route matching.

§Example
// Routes are /api/v1/hello, /api/v1/users, etc.
Server::<API>::new(handlers)
    .nest("/api/v1")
    .serve(addr)
    .await?;
Source

pub fn max_body_size(self, max: usize) -> Self

Set the maximum request body size in bytes.

Bodies exceeding this limit are rejected with 413 Payload Too Large. Default: 2 MiB (2,097,152 bytes).

Source

pub fn with_state<T: Clone + Send + Sync + 'static>(self, state: T) -> Self

Add shared state accessible via State<T> extractors.

Source

pub fn with_static_files(self, prefix: &str, dir: impl Into<PathBuf>) -> Self

Serve static files from a directory at a given URL prefix.

Requests to {prefix}/{path} will serve files from {dir}/{path}. 404 is returned if the file doesn’t exist.

§Example
Server::<API>::new(handlers)
    .with_static_files("/static", "./public")
    .serve(addr)
    .await?;
Source

pub fn with_spa_fallback(self, index_path: impl Into<PathBuf>) -> Self

Serve a file as the fallback for unmatched routes (SPA mode).

When no API route matches, the given file (typically index.html) is served. This enables client-side routing in single-page apps.

§Example
Server::<API>::new(handlers)
    .with_static_files("/static", "./public")
    .with_spa_fallback("./public/index.html")
    .serve(addr)
    .await?;
Source

pub fn with_fallback<S>(self, service: S) -> Self
where S: Service<Request<Incoming>, Response = Response<BoxBody>, Error = Infallible> + Clone + Send + Sync + 'static, S::Future: Send + 'static,

Set a fallback Tower service for requests that don’t match any typeway route.

This enables embedding an Axum router (or any Tower service) inside a typeway server — the reverse of into_axum_router().

§Example
let axum_routes = axum::Router::new()
    .route("/health", get(|| async { "ok" }));

Server::<API>::new(handlers)
    .with_fallback(axum_routes)
    .serve(addr)
    .await?;
Source

pub fn layer<L>(self, layer: L) -> LayeredServer<L::Service>
where L: Layer<RouterService>, L::Service: Service<Request<Incoming>, Response = Response<BoxBody>, Error = Infallible> + Clone + Send + 'static, <L::Service as Service<Request<Incoming>>>::Future: Send + 'static,

Apply a Tower middleware layer to the server.

The layer wraps the entire router service. This is the same API as Axum’s .layer() — any tower::Layer that accepts the router service type can be used.

§Example
use tower_http::trace::TraceLayer;
use tower_http::cors::CorsLayer;

Server::<API>::new(handlers)
    .layer(TraceLayer::new_for_http())
    .layer(CorsLayer::permissive())
    .serve(addr)
    .await?;
Source

pub fn into_service(self) -> RouterService

Get the inner RouterService as a Tower service.

Source

pub fn into_router(self) -> Router

Get the inner router (for integration with other frameworks).

Source

pub async fn serve( self, addr: SocketAddr, ) -> Result<(), Box<dyn Error + Send + Sync>>

Start serving HTTP requests on the given address.

Source

pub async fn serve_with_shutdown( self, listener: TcpListener, shutdown: impl Future<Output = ()> + Send, ) -> Result<(), Box<dyn Error + Send + Sync>>

Start serving with graceful shutdown.

Supports both HTTP/1.1 and HTTP/2 via automatic protocol detection. The server stops accepting new connections when the shutdown future completes. Existing connections are allowed to finish.

§Example
let server = Server::<API>::new(handlers);
let listener = TcpListener::bind("0.0.0.0:3000").await?;

server.serve_with_shutdown(listener, async {
    tokio::signal::ctrl_c().await.ok();
}).await?;

Auto Trait Implementations§

§

impl<A> Freeze for Server<A>

§

impl<A> !RefUnwindSafe for Server<A>

§

impl<A> Send for Server<A>
where A: Send,

§

impl<A> Sync for Server<A>
where A: Sync,

§

impl<A> Unpin for Server<A>
where A: Unpin,

§

impl<A> UnsafeUnpin for Server<A>

§

impl<A> !UnwindSafe for Server<A>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<B, C, R, H> Serves<VersionedApi<B, C, R>> for H
where R: ApiSpec, H: Serves<R>,

Source§

fn register(self, router: &mut Router)

Register all handlers into the router.
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> IsEndpoint<T> for T