百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
O

ohkami

> 编程语言
开源

一个性能出色、声明式且运行时灵活的 Web 框架,适用于 Rust

329 stars0 点赞1 次浏览
访问官网GitHub

工具介绍

一个性能出色、声明式且运行时灵活的 Web 框架,适用于 Rust

  • macro-less and type-safe APIs for declarative, ergonomic code
  • runtime-flexible : tokio, smol, nio, glommio, monoio, compio and worker (Cloudflare Workers), lambda (AWS Lambda)
  • good performance, no-network testing, well-structured middlewares, Server-Sent Events, WebSocket, highly integrated OpenAPI document generation, ...

Quick Start

  1. Add to dependencies :
toml
[dependencies]
ohkami = { version = "0.24", features = ["rt_tokio"] }
tokio  = { version = "1",    features = ["full"] }
  1. Write your first code with Ohkami : examples/quick_start
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
}
  1. Run and check the behavior :
bash
$ cargo run
bash
$ curl http://localhost:3000/healthz
$ curl http://localhost:3000/hello/your_name
Hello, your_name!

Core APIs

Ohkami

Ohkami 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.

Route

Route 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.

fangs

Ohkami'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).

claws

Ohkami 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 format
    • built-ins: Json, Text, Html, UrlEncoded, Multipart
  • param - typed parameters extracted from request
    • built-ins: Path , Query
  • header - types for specific header extracted from request
    • built-ins: types for standard request headers
  • status - types for response with specific status code
    • built-ins: types for standard response status codes

( 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> {
    // ...
}

Feature flags

"rt_tokio", "rt_smol", "rt_nio", "rt_glommio", "rt_monoio", "rt_compio" : native async runtime

  • tokio v1.*.*
  • smol v2.*.*
  • nio v0.1.3*
  • glommio v0.9.*
  • monoio v0.2.*
  • compio v0.17.*

"rt_worker" : Cloudflare Workers

  • worker v0.7.*

Ohkami has first-class support for Cloudflare Workers:

  • #[worker] macro to define a Worker
  • #[bindings], ws::SessionMap helper
  • better DurableObject
  • not require Send Sync bound for handlers or fangs
  • worker_openapi.js script to generate OpenAPI document from #[worker] fn

And also maintains useful project template. Run :

bash
npm create cloudflare <project dir> -- --template https://github.com/ohkami-rs/templates/worker

then <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 repository
  • worker* samples in samples directory
  • #[worker]'s documentation comment in macro definitions

for wokring examples and detailed usage of #[worker] (and/or openapi).

"rt_lambda" : AWS Lambda

  • lambda_runtime v1.0.* with tokio

Both Function URLs and API Gateway are supported, and WebSocket is not supported.

cargo lambda will be good partner. Let's run :

bash
cargo lambda new <project dir> --template https://github.com/ohkami-rs/templates

lambda_runtime::run(your_ohkami) make you_ohkami run on Lambda Function.

Local dev by

bash
cargo lambda watch

and deploy by

bash
cargo lambda build --release [--compiler cargo] [and more]
cargo lambda deploy [--role <arn-of-a-iam-role>] [and more]

See

  • README of template
  • Cargo Lambda document

for details.

"sse" : Server-Sent Events

Ohkami 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" : WebSocket

use 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
}
  • On "rt_worker", both normal ( stateless ) WebSocket and WebSocket on Durable Object are available!
  • On "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

  • Derive openapi::Schema for all your schema structs
  • Make your Ohkami 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

  • customize schemas by manual implemetation of Schema trait
  • customize descriptions or other parts by #[operation] attribute and openapi_* hooks of FromRequest, IntoResponse, Fang (Action)
  • put tags for grouping operations by openapi::Tag fang
…
  • Currently, only JSON is supported as the document format.
  • When the binary size matters, you should prepare a feature flag activating ohkami/openapi in your package, and put all your codes around openapi behind that feature via #[cfg(feature = ...)] or #[cfg_attr(feature = ...)].
  • In 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.

  • Call howls ( as https to http, wss to ws ) instead of howl to run with TLS.
  • You must prepare your own certificate and private key files.
  • Currently, only HTTP/1.1 over TLS is supported.

Example :

bash
$ openssl req -x509 -newkey rsa:4096 -nodes -keyout server.key -out server.crt -days 365 -subj "/CN=localhost"
toml
[dependencies]
ohkami = { version = "0.24", features = ["rt_tokio", "tls"] }
tokio  = { version = "1",    features = ["full"] }
rustls = { version = "0.23", features = ["ring"] }
rustls-pemfile = "2.2"
…
bash
$ cargo run
bash
$ 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 functionalities

  • try response
  • internal performance optimizations

Snippets

Typed content

rust
use 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)
        }
    ))
}

Typed params

…

Middlewares

…

Database connection management with Context fang

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Rustasyncaws-lambdacloudflarecloudflare-workers

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言