Skip to content

Instantly share code, notes, and snippets.

@silmeth
Created May 22, 2024 13:49
Show Gist options
  • Save silmeth/c5ae9af336f7fca872b15de837189a83 to your computer and use it in GitHub Desktop.
Save silmeth/c5ae9af336f7fca872b15de837189a83 to your computer and use it in GitHub Desktop.
use axum::{
async_trait,
extract::{FromRequestParts, Request},
http::{request::Parts, StatusCode},
middleware::Next,
routing::get,
Router,
};
#[derive(Debug)]
struct Foo(i32);
fn new_foo() -> Foo {
Foo(rand::random())
}
#[async_trait]
impl<S> FromRequestParts<S> for Foo
where
S: Send + Sync,
{
type Rejection = StatusCode;
async fn from_request_parts(_: &mut Parts, _: &S) -> Result<Self, Self::Rejection> {
println!("extractor run");
Ok(new_foo())
}
}
#[tokio::main]
async fn main() {
// build our application with a single route
let app = Router::new()
.route(
"/",
get(|foo: Foo| async move {
println!("hello from handler: {foo:?}");
format!("Hello, {foo:?}!")
}),
)
.layer(axum::middleware::from_fn(
|foo: Foo, req: Request, next: Next| async move {
println!("hello from layer: {foo:?}");
next.run(req).await
},
));
// run our app with hyper, listening globally on port 3000
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment