Skip to main content

Handler

Struct Handler 

Source
pub struct Handler { /* private fields */ }
Expand description

Configurable request handler with before/after middleware hooks.

§Example

use dioxus_cloudflare::Handler;
use worker::*;

#[event(fetch)]
async fn fetch(req: Request, env: Env, _ctx: Context) -> Result<Response> {
    unsafe { __wasm_call_ctors(); }

    Handler::new()
        .before(|req| {
            // Short-circuit OPTIONS requests for CORS preflight
            if req.method() == worker::Method::Options {
                let mut resp = Response::empty()?;
                resp.headers_mut().set("Access-Control-Allow-Origin", "*")?;
                resp.headers_mut().set("Access-Control-Allow-Methods", "GET,POST,OPTIONS")?;
                return Ok(Some(resp));
            }
            Ok(None) // continue to Axum dispatch
        })
        .after(|resp| {
            resp.headers_mut().set("Access-Control-Allow-Origin", "*")?;
            Ok(())
        })
        .handle(req, env)
        .await
}

Implementations§

Source§

impl Handler

Source

pub fn new() -> Self

Create a new handler with no middleware hooks.

Source

pub fn before( self, hook: impl Fn(&Request) -> Result<Option<Response>> + 'static, ) -> Self

Add a before-dispatch hook.

Runs after context is set (so cf::env(), cf::d1(), etc. work), before Axum dispatch. Return Ok(None) to continue, Ok(Some(resp)) to short-circuit with a custom response.

Hooks run in the order they were added.

Source

pub fn after(self, hook: impl Fn(&mut Response) -> Result<()> + 'static) -> Self

Add an after-dispatch hook.

Runs after cookies are applied, before returning the response. Use this to add headers, log, or modify the final response.

After hooks also run on short-circuited responses from before hooks. Hooks run in the order they were added.

Source

pub fn session(self, config: SessionConfig) -> Self

Configure session middleware.

When enabled, cf::session() becomes available in server functions. Session data is persisted to the configured backend (KV or D1) and a session cookie is managed automatically.

§Example
use dioxus_cloudflare::prelude::*;

Handler::new()
    .session(SessionConfig::kv("SESSIONS"))
    .handle(req, env)
    .await
Source

pub fn websocket<F, Fut>(self, path: &str, handler: F) -> Self
where F: Fn(Request) -> Fut + 'static, Fut: Future<Output = Result<Response>> + 'static,

Add a WebSocket upgrade route.

When a request has the Upgrade: websocket header and its path starts with path, the handler is called instead of dispatching through Axum. The handler receives the owned worker::Request (to forward to a Durable Object stub, for example).

WebSocket routes are checked after context is set and before hooks run, but before Axum dispatch.

§Example
Handler::new()
    .websocket("/ws", |req| async move {
        let ns = cf::durable_object("WS_DO")?;
        let id = ns.id_from_name("default").cf()?;
        let stub = id.get_stub().cf()?;
        Ok(stub.fetch_with_request(req).await.cf()?)
    })
    .handle(req, env)
    .await
Source

pub async fn handle(&self, req: Request, env: Env) -> Result<Response>

Dispatch the request through registered #[server] functions.

This is the async entry point — call it from #[event(fetch)].

Trait Implementations§

Source§

impl Default for Handler

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> InitializeFromFunction<T> for T

Source§

fn initialize_from_function(f: fn() -> T) -> T

Create an instance of this type from an initialization function
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<Ret> SpawnIfAsync<(), Ret> for Ret

Source§

fn spawn(self) -> Ret

Spawn the value into the dioxus runtime if it is an async block
Source§

impl<T, O> SuperFrom<T> for O
where O: From<T>,

Source§

fn super_from(input: T) -> O

Convert from a type to another type.
Source§

impl<T, O, M> SuperInto<O, M> for T
where O: SuperFrom<T, M>,

Source§

fn super_into(self) -> O

Convert from a type to another type.
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<S, T> Upcast<T> for S
where T: UpcastFrom<S> + ?Sized, S: ?Sized,

Source§

fn upcast(&self) -> &T
where Self: ErasableGeneric, T: ErasableGeneric<Repr = Self::Repr>,

Perform a zero-cost type-safe upcast to a wider ref type within the Wasm bindgen generics type system. Read more
Source§

fn upcast_into(self) -> T
where Self: Sized + ErasableGeneric, T: ErasableGeneric<Repr = Self::Repr>,

Perform a zero-cost type-safe upcast to a wider type within the Wasm bindgen generics type system. Read more
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more