Created
December 23, 2021 15:27
-
-
Save davidpdrsn/2890612d4e2b9e419b3bf64fce081272 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use axum::{ | |
extract::{Extension, Path}, | |
routing::get, | |
AddExtensionLayer, Router, | |
}; | |
use hyper::service::make_service_fn; | |
use std::{ | |
convert::Infallible, | |
sync::{Arc, Mutex}, | |
}; | |
use tower::Layer; | |
#[tokio::main] | |
async fn main() { | |
let app = Router::new().route("/add-route/:path", get(add_route)); | |
let shared_app = Arc::new(Mutex::new(app.clone())); | |
let make_service = make_service_fn(|_| { | |
let app = shared_app.clone().lock().unwrap().clone(); | |
let app = AddExtensionLayer::new(shared_app.clone()).layer(app); | |
async move { Ok::<_, Infallible>(app) } | |
}); | |
axum::Server::bind(&"0.0.0.0:3000".parse().unwrap()) | |
.serve(make_service) | |
.await | |
.unwrap(); | |
} | |
async fn add_route( | |
Extension(shared_app): Extension<Arc<Mutex<Router>>>, | |
Path(path): Path<String>, | |
) -> String { | |
let shared_app = &mut *shared_app.lock().unwrap(); | |
{ | |
let path = path.clone(); | |
*shared_app = shared_app.clone().route( | |
&format!("/{}", path), | |
get(|| async move { format!("Dynamic route `GET /{}` called", path.clone()) }), | |
); | |
} | |
format!("Dynamic route `GET /{}` added", path) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Finally, I implemented this with a shared pointer