Files
axum/examples/versioning/src/main.rs
T

73 lines
1.9 KiB
Rust
Raw Normal View History

2021-08-02 23:09:09 +02:00
//! Run with
//!
//! ```not_rust
//! cargo run -p example-versioning
2021-08-02 23:09:09 +02:00
//! ```
2021-07-22 13:23:50 +02:00
use axum::{
async_trait,
extract::{FromRequestParts, Path},
http::{request::Parts, StatusCode},
response::{IntoResponse, Response},
routing::get,
RequestPartsExt, Router,
2021-07-22 13:23:50 +02:00
};
use std::collections::HashMap;
2022-03-06 12:37:00 +01:00
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
2021-06-13 13:50:56 +02:00
#[tokio::main]
async fn main() {
2022-03-06 12:37:00 +01:00
tracing_subscriber::registry()
.with(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| "example_versioning=debug".into()),
)
2022-03-06 12:37:00 +01:00
.with(tracing_subscriber::fmt::layer())
.init();
2021-06-13 13:50:56 +02:00
// build our application with some routes
let app = Router::new().route("/:version/foo", get(handler));
2021-06-13 13:50:56 +02:00
// run it
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
2021-06-19 12:50:33 +02:00
.await
.unwrap();
tracing::debug!("listening on {}", listener.local_addr().unwrap());
axum::serve(listener, app).await.unwrap();
2021-06-13 13:50:56 +02:00
}
async fn handler(version: Version) {
2023-09-19 02:51:57 -04:00
println!("received request with version {version:?}");
2021-06-13 13:50:56 +02:00
}
#[derive(Debug)]
enum Version {
V1,
V2,
V3,
}
#[async_trait]
impl<S> FromRequestParts<S> for Version
2021-06-19 12:50:33 +02:00
where
2022-08-17 22:08:24 +02:00
S: Send + Sync,
2021-06-19 12:50:33 +02:00
{
type Rejection = Response;
2021-06-13 13:50:56 +02:00
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
let params: Path<HashMap<String, String>> =
parts.extract().await.map_err(IntoResponse::into_response)?;
2021-06-13 13:50:56 +02:00
let version = params
.get("version")
.ok_or_else(|| (StatusCode::NOT_FOUND, "version param missing").into_response())?;
2021-08-06 16:17:57 +08:00
match version.as_str() {
2021-06-13 13:50:56 +02:00
"v1" => Ok(Version::V1),
"v2" => Ok(Version::V2),
"v3" => Ok(Version::V3),
_ => Err((StatusCode::NOT_FOUND, "unknown version").into_response()),
}
}
}