Crate worker_route
source ·Expand description
Worker Route is a crate designed for usage in Cloudflare Workers.
Examples
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
}
Features
- Add routes to handler with macro attribute
- Extract query parameters or path from URL
Re-exports
pub use crate::http::HttpHeaders;
pub use crate::http::HttpRequest;
pub use crate::http::HttpResponse;
pub use crate::http::Responder;
pub use crate::http::ResponseError;
Modules
- Various HTTP related types
Structs
- Top level Worker-Route Error.
- Extract typed information with the supplied struct and deserialize it with
worker::Url
.
Enums
- All possible Error variants that may occur when working with
worker_route
.
Traits
- Implemented for
worker::Router
to configure the route’s pattern. - Implemented for
worker::Router
to run external route configuration. - A handler middleware provides an access to
worker::Request
Attribute Macros
- A macro that creates route handler with
worker::Router::delete
- A macro that creates route handler with
worker::Router::get
- A macro that creates route handler with
worker::Router::head
- A macro that creates route handler with
worker::Router::options
- A macro that creates route handler with
worker::Router::patch
- A macro that creates route handler with
worker::Router::post
- A macro that creates route handler with
worker::Router::put
- A macro that creates route handler with multiple methods.