#cloudflare-workers #worker #serverless #web #http #query-parameters #request-response

worker-route

Cloudflare Workers 的路由处理程序和数据提取器

3 个版本

0.0.3 2023年11月9日
0.0.2 2023年9月29日
0.0.1 2023年8月27日

#1085 in Web 编程

Apache-2.0

84KB
1.5K SLoC

worker-route

Worker Route 是一个为 Cloudflare Workers 设计的 crate。

示例

use serde::{Deserialize, Serialize};
use worker::{event, Env, Request, Response, Result, RouteContext, Router};
use worker_route::{get, Configure, Query, Service};

#[derive(Debug, Serialize, Deserialize)]
struct Bar {
    bar: String,
}

#[get("/bar")]
async fn bar(req: Query<Bar>, _: RouteContext<()>) -> Result<Response> {
    Response::from_json(&req.into_inner())
}

#[derive(Debug, Serialize, Deserialize)]
struct Foo {
    foo: String,
}

#[get("/foo")]
async fn foo(req: Query<Foo>, _: RouteContext<()>) -> Result<Response> {
    Response::from_json(&req.into_inner())
}


#[derive(Debug, Serialize, Deserialize)]
struct FooBar {
    foo: String,
    bar: String,
}

// your function can consist of (Query<T>, Request, RouteContext<()>) too
#[get("/foo-bar")]
async fn foo_bar(req: Query<FooBar>, _req: Request, _: RouteContext<()>) -> Result<Response> {
    Response::from_json(&req.into_inner())
}

#[derive(Debug, Deserialize, Serialize)]
struct Person {
    name: String,
    age: usize,
}

#[get("/person/:name/:age")]
async fn person(req: Query<Person>, _: RouteContext<()>) -> Result<Response> {
    Response::from_json(&req.into_inner())
}

fn init_routes(router: Router<'_, ()>) -> Router<'_, ()> {
    router
        .configure(bar)
        .configure(foo)
        .configure(person)
        .configure(foo_bar)
}

#[event(fetch)]
pub async fn main(req: Request, env: Env, _ctx: worker::Context) -> Result<Response> {
    let router = Router::new();
    router.service(init_routes).run(req, env).await
}

特性

  • 使用宏属性添加路由到处理器
  • 从 URL 提取查询参数或路径

许可证:Apache-2.0

依赖项

~13–18MB
~353K SLoC