Crates.io | axum-cloudflare-adapter |
lib.rs | axum-cloudflare-adapter |
version | 0.13.0 |
source | src |
created_at | 2023-02-27 15:24:54.202404 |
updated_at | 2024-09-27 03:34:45.310781 |
description | An adapter to easily run an Axum server in a Cloudflare worker. |
homepage | |
repository | https://github.com/logankeenan/axum-cloudflare-adapter |
max_upload_size | |
id | 796118 |
size | 13,603 |
An adapter to easily run an Axum server in a Cloudflare worker.
Axum support in workers-rs is enabled by the http feature in worker-rs.
This is possible because both Axum and worker-rs http uses the same http crate.
This adapter can be used as an easy way to migrate from the non http workers-rs version to the http version:
.or_else_any_method_async("/*catchall", |_, ctx| async move {
use worker::*;
use axum::{
response::{Html},
routing::get,
Router as AxumRouter,
extract::State,
};
use axum_cloudflare_adapter::{to_axum_request, to_worker_response, wasm_compat, EnvWrapper};
use tower_service::Service;
use std::ops::Deref;
#[derive(Clone)]
pub struct AxumState {
pub env_wrapper: EnvWrapper,
}
#[wasm_compat]
async fn index(State(state): State<AxumState>) -> Html<&'static str> {
let env: &Env = state.env_wrapper.env.deref();
let worker_rs_version: Var = env.var("WORKERS_RS_VERSION").unwrap();
console_log!("WORKERS_RS_VERSION: {}", worker_rs_version.to_string());
Html("<p>Hello from Axum!</p>")
}
#[event(fetch)]
pub async fn main(req: Request, env: Env, _ctx: worker::Context) -> Result<Response> {
let mut _router: AxumRouter = AxumRouter::new()
.route("/", get(index))
.with_state(AxumState {
env_wrapper: EnvWrapper::new(env),
});
let axum_request = to_axum_request(req).await.unwrap();
let axum_response = _router.call(axum_request).await.unwrap();
let response = to_worker_response(axum_response).await.unwrap();
Ok(response)
}
cd adapter && wasm-pack test --firefox --headless
cd adapter && cargo build --target wasm32-unknown-unknown
The /example
directory contains a Cloudflare worker running an Axum sever