Skip to main content

Module axum

Module axum 

Source
Available on crate feature axum only.
Expand description

This module integrates the cloudevents-sdk with Axum web service framework to easily send and receive CloudEvents.

To deserialize an HTTP request as CloudEvent

To echo events:

use axum_lib as axum;
use axum::{
    routing::{get, post},
    Router,
};
use cloudevents::Event;
use http::StatusCode;

fn app() -> Router {
    Router::new()
        .route("/", get(|| async { "hello from cloudevents server" }))
        .route(
            "/",
            post(|event: Event| async move {
                println!("received cloudevent {}", &event);
                (StatusCode::OK, event)
            }),
        )
}

To create event inside request handlers and send them as responses:

use axum_lib as axum;
use axum::{
    routing::{get, post},
    Router,
};
use cloudevents::{Event, EventBuilder, EventBuilderV10};
use http::StatusCode;
use serde_json::json;

fn app() -> Router {
    Router::new()
        .route("/", get(|| async { "hello from cloudevents server" }))
        .route(
            "/",
            post(|| async move {
                let event = EventBuilderV10::new()
                    .id("1")
                    .source("url://example_response/")
                    .ty("example.ce")
                    .data(
                        mime::APPLICATION_JSON.to_string(),
                        json!({
                            "name": "John Doe",
                            "age": 43,
                            "phones": [
                                "+44 1234567",
                                "+44 2345678"
                            ]
                        }),
                    )
                    .build()
                    .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;

                Ok::<Event, (StatusCode, String)>(event)
            }),
        )
}

Modulesยง

extract
response