#[event]
Expand description
The event
macro is used to denote a Worker handler, essentially binding from
the JS runtime to a Rust function.
As of right now, the following attributes are supported:
fetch
: Fetch Handlerscheduled
: Scheduled Handlerqueue
: Queue Handler- This attribute is only available when the
queue
feature is enabled.
- This attribute is only available when the
start
: merely creates a wasm-bindgen start functionrespond_with_errors
: if this attribute is present, the function will return aResponse
object with a 500 status code and the status text of the error message, if an error occurs
The macro is expanded into a different function signature, depending on the attributes used
§Fetch
At a high-level, the fetch
handler is used to handle incoming HTTP requests. The function signature for a fetch
handler is conceptually something like:
async fn fetch(req: impl From<web_sys::Request>, env: Env, ctx: Context) -> Result<impl Into<web_sys::Response>, impl Into<Box<dyn Error>>>
In other words, it takes some “request” object that can be derived from a web_sys::Request
(into whatever concrete Request type you like),
and returns some “response” object that can be converted into a web_sys::Response
(from whatever concrete Response type you like).
Error types can be any type that implements [std::error::Error
].
In practice, the “request” and “response” objects are usually one of these concrete types, supported out of the box:
§worker::{Request, Response}
#[event(fetch, respond_with_errors)]
async fn main(req: worker::Request, env: Env, ctx: Context) -> Result<worker::Response> {
worker::Response::ok("Hello World (worker type)")
}
§web_sys::{Request, Response}
#[event(fetch, respond_with_errors)]
async fn main(req: web_sys::Request, env: Env, ctx: Context) -> Result<web_sys::Response> {
Ok(web_sys::Response::new_with_opt_str(Some("Hello World (native type)".into())).unwrap())
}
§axum (with http
feature)
#[event(fetch)]
async fn fetch(req: HttpRequest, env: Env, ctx: Context) -> Result<http::Response<axum::body::Body>> {
Ok(router().call(req).await?)
}