A performant, declarative, and runtime-flexible web framework for Rust
A performant, declarative, and runtime-flexible web framework for Rust
tokio, smol, nio, glommio, monoio, compio and worker (Cloudflare Workers), lambda (AWS Lambda)dependencies :[dependencies]
ohkami = { version = "0.24", features = ["rt_tokio"] }
tokio = { version = "1", features = ["full"] }use ohkami::{Ohkami, Route};
use ohkami::claw::{Path, status};
async fn health_check() -> status::NoContent {
status::NoContent
}
async fn hello(Path(name): Path) -> String {
format!("Hello, {name}!")
}
#[tokio::main]
async fn main() {
Ohkami::new((
"/healthz"
.GET(health_check),
"/hello/:name"
.GET(hello),
)).howl("localhost:3000").await
}$ cargo run$ curl http://localhost:3000/healthz
$ curl http://localhost:3000/hello/your_name
Hello, your_name!OhkamiOhkami is the main entry point of Ohkami application:
a collection of Routes and Fangs, and provides .howl()/.howls() method to run the application.
Ohkami::new((
// global fangs
Fang1,
Fang2,
// routes
"/hello"
.GET(hello_handler)
.POST(hello_post_handler),
"/goodbye"
.GET((
// local fangs
Fang3,
Fang4,
goodbye_handler // handler
)),
)).howl("localhost:3000").await;.howls() (tls feature only) is used to run Ohkami with TLS (HTTPS) support
upon rustls ecosystem.
howl(s) supports graceful shutdown by Ctrl-C ( SIGINT ) on native runtimes.
RouteRoute is the core trait to define Ohkami's routing:
.GET(), .POST(), .PUT(), .PATCH(), .DELETE(), .OPTIONS() to define API endpoints.By({another Ohkami}) to nest Ohkamis.Mount({directory path}) to serve static directory
(pre-compressed files with gzip, deflate, br, zstd are supported)Here GET, POST, etc. takes a handler function:
async fn({FromRequest type},*) -> {IntoResponse type}On native runtimes, whole a handler must be Send + Sync + 'static
and the return future must be Send + 'static.
fangsOhkami's request handling system is called fang; all handlers and middlewares are built on it.
/* simplified for description */
pub trait Fang {
type Proc: FangProc;
fn chain(&self, inner: Inner) -> Self::Proc;
}
pub trait FangProc {
async fn bite(&'b self, req: &'b mut Request) -> Response;
}built-ins:
BasicAuth, Cors, Csrf, Jwt (authentication/security)Context (reuqest context)Enamel (security headers; experimantal)Timeout (handling timeout; native runtimes only)openapi::Tag (tag for OpenAPI document generation; openapi feature only)Ohkami provides FangAction utility trait to implement Fang trait easily:
/* simplified for description */
pub trait FangAction {
async fn fore(&'a self, req: &'a mut Request) -> Result {
// default implementation is empty
Ok(())
}
async fn back(&'a self, res: &'a mut Response) {
// default implementation is empty
}
}Additionally, you can apply fangs both as global fangs to an Ohkami or
as local fangs to a specific handler (described below).
clawsOhkami provides claw API: handler parts designed for declarative way to
extract request data and construct response data:
content - typed content {extracted from request / for response} of specific formatJson, Text, Html, UrlEncoded, Multipartparam - typed parameters extracted from requestPath , Queryheader - types for specific header extracted from requeststatus - types for response with specific status code( here T means a type that implements serde::Deserialize for request and serde::Serialize for response, and P means a type that implements FromParam or a tuple of such types. )
The number of path parameters extracted by Path is automatically asserted
to be the same or less than the number of path parameters contained in the route path
when the handler is registered to routing.
async fn handler0(
Path(param): Path,
) -> Json {
// ...
}
async fn handler1(
Json(req): Json,
Path((param0, param1)): Path,
Query(query): Query,
) -> status::Created> {
// ...
}"rt_tokio", "rt_smol", "rt_nio", "rt_glommio", "rt_monoio", "rt_compio" : native async runtime"rt_worker" : Cloudflare WorkersOhkami has first-class support for Cloudflare Workers:
#[worker] macro to define a Worker#[bindings], ws::SessionMap helperDurableObjectSend Sync bound for handlers or fangs#[worker] fnAnd also maintains useful project template. Run :
npm create cloudflare <project dir> -- --template https://github.com/ohkami-rs/templates/workerthen <project dir> will have wrangler.jsonc, package.json and a Rust library crate.
#[ohkami::worker] async? fn({bindings}?) -> Ohkami is the Worker definition.
Local dev by npm run dev and deploy by npm run deploy !
See
worker* temaplates in template repositoryworker* samples in samples directory#[worker]'s documentation comment in macro definitionsfor wokring examples and detailed usage of #[worker] (and/or openapi).
"rt_lambda" : AWS LambdatokioBoth Function URLs and API Gateway are supported, and WebSocket is not supported.
cargo lambda will be good partner. Let's run :
cargo lambda new <project dir> --template https://github.com/ohkami-rs/templateslambda_runtime::run(your_ohkami) make you_ohkami run on Lambda Function.
Local dev by
cargo lambda watchand deploy by
cargo lambda build --release [--compiler cargo] [and more]
cargo lambda deploy [--role <arn-of-a-iam-role>] [and more]See
for details.
"sse" : Server-Sent EventsOhkami responds with HTTP/1.1 Transfer-Encoding: chunked.
Use some reverse proxy to do with HTTP/2,3.
use ohkami::{Ohkami, Route};
use ohkami::sse::DataStream;
use tokio::time::{sleep, Duration};
async fn handler() -> DataStream {
DataStream::new(|mut s| async move {
s.send("starting streaming...");
for i in 1..=5 {
sleep(Duration::from_secs(1)).await;
s.send(format!("MESSAGE #{i}"));
}
s.send("streaming finished!");
})
}
#[tokio::main]
async fn main() {
Ohkami::new((
"/sse".GET(handler),
)).howl("localhost:3020").await
}"ws" : WebSocketuse ohkami::{Ohkami, Route};
use ohkami::ws::{WebSocketContext, WebSocket, Message};
async fn echo_text(ctx: WebSocketContext) -> WebSocket {
ctx.upgrade(|mut conn| async move {
while let Ok(Some(Message::Text(text))) = conn.recv().await {
conn.send(text).await.expect("failed to send text");
}
})
}
#[tokio::main]
async fn main() {
Ohkami::new((
"/ws".GET(echo_text),
)).howl("localhost:3030").await
}"rt_worker", both normal ( stateless ) WebSocket and WebSocket on Durable Object are available!"rt_lambda", WebSocket is currently not supported."openapi" : OpenAPI document generation"openapi" provides highly integrated OpenAPI support.
This enables macro-less, as consistent as possible OpenAPI document generation, where most of the consistency between document and behavior is automatically assured by Ohkami's internal work.
Only you have to
openapi::Schema for all your schema structsOhkami call .generate(openapi::OpenAPI { ... })to generate consistent OpenAPI document.
You don't need to take care of writing accurate methods, paths, parameters, contents, ... for this OpenAPI feature; All they are done by Ohkami.
Of course, you can flexibly
Schema trait#[operation] attribute and openapi_* hooks of FromRequest, IntoResponse, Fang (Action)tags for grouping operations by openapi::Tag fang…ohkami/openapi in your package, and put all your codes around openapi behind that feature via #[cfg(feature = ...)] or #[cfg_attr(feature = ...)].rt_worker, .generate is not available because Ohkami can't have access to your local filesystem by wasm32 binary on Minifalre. So ohkami provides a CLI tool to generate document from #[ohkami::worker] Ohkami with openapi feature."tls"HTTPS support up on rustls ecosystem.
howls ( as https to http, wss to ws ) instead of howl to run with TLS.Example :
$ openssl req -x509 -newkey rsa:4096 -nodes -keyout server.key -out server.crt -days 365 -subj "/CN=localhost"[dependencies]
ohkami = { version = "0.24", features = ["rt_tokio", "tls"] }
tokio = { version = "1", features = ["full"] }
rustls = { version = "0.23", features = ["ring"] }
rustls-pemfile = "2.2"…$ cargo run$ curl https://localhost:8443 --insecure # for self-signed certificate
Hello, secure ohkami!For localhost-testing with browser (or curl without --insecure),
mkcert is highly recommended.
"nightly" : nightly-only functionalitiesuse ohkami::claw::{Json, status};
use ohkami::serde::{Deserialize, Serialize};
/* Deserialize for request */
#[derive(Deserialize)]
struct CreateUserRequest {
name: &'req str,
password: &'req str,
}
/* Serialize for response */
#[derive(Serialize)]
struct User {
name: String,
}
async fn create_user(
Json(req): Json>
) -> status::Created> {
status::Created(Json(
User {
name: String::from(req.name)
}
))
}……Context fangNo open issues yet, or sync has not completed.