mini-serve 0.5.0

An HTTP server: trie router, middleware, CORS, optional TLS. Built on hyper + tokio.
Documentation
use std::convert::Infallible;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

use hyper::body::{Bytes, Incoming};
use hyper::{Request, Response};
use http_body_util::combinators::BoxBody;
use http_body_util::Full;

use crate::error::ServeError;
use crate::state::State;

/// The response body type used by all handlers.
pub type ResponseBody = BoxBody<Bytes, Infallible>;

/// Create a response body from raw bytes.
pub fn body(bytes: Bytes) -> ResponseBody {
	BoxBody::new(Full::new(bytes))
}

/// A request handler that processes an HTTP request and returns a response or error.
///
/// Handlers receive the full request (method, path, headers, body) and the app state,
/// and return either a response or a `ServeError` (which is converted to an HTTP error response).
pub type Handler<S> = Arc<
	dyn Fn(Request<Incoming>, State<S>)
			-> Pin<Box<dyn Future<Output = Result<Response<ResponseBody>, ServeError>> + Send>>
		+ Send
		+ Sync,
>;

/// Wrap an async function to create a handler.
///
/// # Example
///
/// ```ignore
/// use mini_serve::handler;
/// use hyper::StatusCode;
/// use hyper::body::Bytes;
///
/// let h = handler(|req, state| async move {
///     Ok::<_, mini_serve::ServeError>(
///         mini_serve::json(StatusCode::OK, &serde_json::json!({"status": "ok"}))
///     )
/// });
/// ```
pub fn handler<S, F, Fut>(f: F) -> Handler<S>
where
	S: Send + Sync + 'static,
	F: Fn(Request<Incoming>, State<S>) -> Fut + Send + Sync + 'static,
	Fut: Future<Output = Result<Response<ResponseBody>, ServeError>> + Send + 'static,
{
	Arc::new(move |req, state| Box::pin(f(req, state)))
}