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
2022-04-29 18:53:41 +02:00
//! cd examples && 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, net::SocketAddr};
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::new(
std::env::var("RUST_LOG").unwrap_or_else(|_| "example_versioning=debug".into()),
))
.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 addr = SocketAddr::from(([127, 0, 0, 1], 3000));
tracing::debug!("listening on {}", addr);
axum::Server::bind(&addr)
2021-06-19 12:50:33 +02:00
.serve(app.into_make_service())
.await
.unwrap();
2021-06-13 13:50:56 +02:00
}
async fn handler(version: Version) {
println!("received request with version {:?}", version);
}
#[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()),
}
}
}