Expand description
Tako is a multi-transport Rust web framework: one router, middleware stack, and observability model for HTTP/1.1, HTTP/2, HTTP/3, WebSocket, SSE, gRPC, TCP, UDP, and Unix sockets, on Tokio or Compio.
The package on crates.io is tako-rs; the library it provides is tako. The
separate tako crate on crates.io is an unrelated project.
§Quickstart
[dependencies]
tako-rs = "2.5"
tokio = { version = "1", features = ["macros", "net", "rt-multi-thread"] }use tako::{router::Router, types::BoxError, Server};
use tokio::net::TcpListener;
#[tokio::main]
async fn main() -> Result<(), BoxError> {
let mut router = Router::new();
router.get("/", || async { "Hello, Tako!" });
let listener = TcpListener::bind("127.0.0.1:8080").await?;
Server::builder()
.build()
.try_spawn_http(listener, router)?
.result()
.await?;
Ok(())
}§Handlers and extractors
Handlers are async functions. Their arguments are extractors that pull typed
data out of the request, and their return values implement
Responder. Only the last argument may consume the
body.
use serde::{Deserialize, Serialize};
use tako::extractors::{json::Json, path::Path, state::State};
use tako::{responder::Responder, router::Router, StatusCode};
#[derive(Clone)]
struct AppState {
greeting: String,
}
#[derive(Deserialize)]
struct NewUser {
name: String,
}
#[derive(Serialize)]
struct User {
id: u64,
name: String,
}
async fn show_user(Path(id): Path<u64>, State(state): State<AppState>) -> String {
format!("{}, user {id}", state.greeting)
}
async fn create_user(Json(new): Json<NewUser>) -> impl Responder {
(StatusCode::CREATED, Json(User { id: 1, name: new.name }))
}
let mut router = Router::new();
router.with_state(AppState { greeting: "Hello".into() });
router.get("/users/{id}", show_user);
router.post("/users", create_user);§Feature flags
The default build serves HTTP/1.1, raw TCP, and Unix sockets on Tokio, with the core extractors and middleware. Everything else is opt-in:
| Feature | Enables |
|---|---|
http2, http3, tls | HTTP/2 including h2c, HTTP/3 over QUIC, and rustls TLS |
ws, sse, udp | WebSocket upgrades, Server-Sent Events, and UDP servers |
grpc, protobuf | gRPC over HTTP/2 and protobuf bodies |
plugins | CORS, compression, rate limiting, and idempotency |
signals, queue-cron | In-process signals and cron-scheduled queue jobs |
metrics-prometheus, metrics-opentelemetry | Metrics export |
async-graphql, utoipa, vespera | GraphQL and OpenAPI integrations |
per-thread | Thread-per-core server |
compio | The Compio runtime: io_uring on Linux, IOCP on Windows |
The feature reference lists every flag.
§Learn more
- Guide, also as llms.txt for AI assistants
- Runnable examples
- Coming from Axum
§Crate layout
This umbrella crate stitches together the workspace sub-crates:
tako-rs-core: routing, handlers, middleware and plugin traits, body and request types, state, signals, queue, WebSocket, plus GraphQL, gRPC, andOpenAPIhelperstako-rs-extractors: concrete request extractors (cookies, form, query, path, JWT, multipart, SIMD JSON, …)tako-rs-server: HTTP/1, TLS, HTTP/3, WebTransport, raw TCP, UDP, and Unix sockets, PROXY protocol, plus the Compio variantstako-rs-streams: SSE, file streaming, static file serving, and raw QUIC sessionstako-rs-plugins: built-in middleware (auth, CSRF, sessions, …) and plugins (CORS, compression, rate limiting, idempotency, metrics)
Public APIs are re-exported under tako::* according to the selected features.
Modules§
- body
TakoBody, the body of every request and response.- config
Config, typed configuration loaded from environment variables.- conn_
info ConnInfo, which every transport adds to request extensions next to its own entries, such asSocketAddrorUnixPeerAddr.- extractors
- Request data extraction utilities.
- file_
stream file-stream - Streamed file responses, plus the precondition and
ETaghelpers behind them. - graphiql
graphiql GraphiQLIDE page for aGraphQLendpoint.- graphql
async-graphql async-graphqlextractors, responders and WebSocket subscriptions.- grpc
grpc - gRPC over HTTP/2: each method is a
POST /<package>.<Service>/<Method>route, andOption<GrpcDeadline>extracts the client’sgrpc-timeout. - header
- HTTP header types
- middleware
- Middleware for processing requests and responses in a pipeline.
- openapi
utoipaorvespera OpenAPIroute metadata plus two spec backends:utoipa(derive macros, recommended) andvespera(a spec built at runtime, also from the routes’ metadata).- plugins
plugins - prelude
- The types most handlers need, for
use tako::prelude::*;. Modules stay at their canonical paths, such astako::extractorsandtako::middleware. - problem
- RFC 7807 / RFC 9457
application/problem+jsonerror responses. - proxy_
protocol proxy-protocol - PROXY protocol v1 (text) and v2 (binary) parsing, for the real client address a load balancer
such as
HAProxyor AWS NLB prepends to each TCP connection. - queue
- In-memory background job queue with retries, delayed and deduplicated jobs, a dead letter queue and graceful shutdown.
- redirect
Redirectresponses and an HTTP-to-HTTPS redirect router.- responder
- The
Respondertrait, which turns handler return values into responses. - route
- The
Routethat router registration returns, for configuring that one route. - router
- The
Router, which matches requests to routes and runs them through middleware. - router_
state - Per-router typed state;
State<T>reads it before falling back to the process-globalget_state. - server_
tcp - Raw TCP servers that hand each accepted stream to a handler, on Tokio or compio.
- server_
tls_ compio compio-tls - TLS HTTP server on compio; HTTP/2 over ALPN
h2runs on thesend_wrapperglue incompio_h2. - server_
udp udp - Raw UDP servers that hand each datagram to a handler, on Tokio or compio.
- server_
unix Unix - Raw and HTTP servers on Unix domain sockets. A path starting with
@names a Linux abstract socket, which skips the stale-file cleanup and the removal after shutdown. - signals
signals - In-process named signals for cross-cutting hooks such as metrics, logging and app events.
- socket_
activation socket-activation - Listening sockets inherited through systemd, s6 or catflap socket activation (
LISTEN_FDS), as Tokio types; indexes follow the order the unit file declares them in. - sse
sse - Server-Sent Events. Responses send
Cache-Control: no-cache, no-store, must-revalidateandX-Accel-Buffering: no, so neither caches nor nginx hold events back. - state
- Process-global state with one slot per type; prefer
Router::with_statefor router-scoped values. - static
ServeDirfor a directory tree, with index files,.br/.gzsidecars, an SPA fallback and traversal checks, andServeFilefor one file.- stores
- Pluggable backend traits for stateful middleware (sessions, rate limiting, …).
- tls
compio-tlsorhttp3ortls - Shared PEM loading for TLS transports.
- tracing
tako-tracing - A
tracing-subscriberformatter with source locations, installed byinit_tracing. - types
- Request, response and middleware type aliases used across the framework.
- webtransport
webtransport - W3C WebTransport sessions on the HTTP/3 server, on either runtime; on Tokio also
RawQuicSession, a plain QUIC endpoint for peers that do not speak WebTransport. - ws
ws - WebSocket (RFC 6455) server connections.
- zero_
copy_ extractors zero-copy-extractors - Borrowing variants of the body, JSON, form, query, path and header extractors. The body ones collect the body once into the request extensions and borrow from it.
Structs§
- Accept
Backoff - Exponential backoff for accept loops, whose errors (e.g.
EMFILE) are transient rather than fatal to the listener. - Bytes
- A cheaply cloneable and sliceable chunk of contiguous memory.
- Compio
Server compio - Compio-runtime server (
io_uringon Linux, IOCP on Windows, kqueue on macOS) with the TokioServerAPI. Construct withCompioServer::builder. - Compio
Server Builder compio - Fluent constructor for the compio-runtime
CompioServer. - Full
- A body that consists of a single chunk.
- Jemalloc
jemalloc - Handle to the jemalloc allocator
- Method
- The Request Method (VERB)
- PerThread
Config per-thread - Configuration for
serve_per_threadandspawn_per_thread. - PerThread
Shutdown per-thread - Stops the workers of
spawn_per_thread; the signal is sticky, so a worker that starts waiting aftertriggerstill sees it. - Reloadable
Resolver compio-tlsorhttp3ortls - Certificate resolver whose key can be swapped at runtime; keep the
Arcpassed toTlsCert::resolverto reload. Each handshake costs one lock-freeArcclone. - Server
Config - Limits and timeouts shared by every transport; pass it to the server builder’s
config. - Server
Error - A clonable server startup or background-task failure.
- Server
Handle - Handle to a spawned server on either runtime. Dropping it does not stop the server; call
ServerHandle::shutdown, orServerHandle::triggerand thenjoin, to drain it. - Status
Code - An HTTP status code (
status-codein RFC 9110 et al.).
Enums§
- Client
Auth compio-tlsorhttp3ortls - mTLS policy: client certificates are verified against the
rustls::RootCertStore. - H3Congestion
- QUIC congestion controller for HTTP/3, from
quinn::congestionwithout a quinn dependency. - TlsCert
- Certificate source for
spawn_tlsandspawn_h3;DerandResolverneed thetlsfeature.
Constants§
- NOT_
FOUND - Plain-text 404 response, e.g. for
router.fallback(|_| async { NOT_FOUND }).
Functions§
- bind_
with_ port_ fallback - Binds
addr, asking on stdin whether to try the next port while the port is in use; meant for local development and examples. - build_
rustls_ server_ config compio-tlsorhttp3ortls - Builds the rustls config the TLS spawn methods use, for the
serve_*_with_rustls_configfunctions. Withh3inalpn, 0-RTT early data is disabled. - serve_
per_ thread per-thread - Runs workers until Ctrl+C or SIGTERM, then drains requests; fails if no worker could bind.
- shutdown_
signal - Waits for Ctrl+C or, on Unix, SIGTERM, using a dedicated signal driver when called outside Tokio.
- spawn_
per_ thread per-thread - Starts workers and returns their thread handles and the trigger that stops them.
Attribute Macros§
- delete
#[delete("/path", [name = "Foo"])]— shorthand for#[route(DELETE, ...)].- get
#[get("/path", [name = "Foo"])]— shorthand for#[route(GET, ...)].- head
#[head("/path", [name = "Foo"])]— shorthand for#[route(HEAD, ...)].- options
#[options("/path", [name = "Foo"])]— shorthand for#[route(OPTIONS, ...)].- patch
#[patch("/path", [name = "Foo"])]— shorthand for#[route(PATCH, ...)].- post
#[post("/path", [name = "Foo"])]— shorthand for#[route(POST, ...)].- put
#[put("/path", [name = "Foo"])]— shorthand for#[route(PUT, ...)].- route
- Registers the handler for
Router::mount_all; typed placeholders such as{id: u64}also generate aTypedParamsstruct named<Handler>Paramsunlessname = "..."overrides it.