Skip to content
Myr

main.rs

This file

Path

examples/versioning/src/main.rs

112 lines · 3.0 KiB · Rust

Last changed by

examples: Simplify Request and Response construction (#3653)tottotobefore adoption3f8956d

History of this file

Take it

1//! Run with2//!3//! ```not_rust4//! cargo run -p example-versioning5//! ```67use axum::{8    extract::{FromRequestParts, Path},9    http::{request::Parts, StatusCode},10    response::{Html, IntoResponse, Response},11    routing::get,12    RequestPartsExt, Router,13};14use std::collections::HashMap;15use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};1617#[tokio::main]18async fn main() {19    tracing_subscriber::registry()20        .with(21            tracing_subscriber::EnvFilter::try_from_default_env()22                .unwrap_or_else(|_| format!("{}=debug", env!("CARGO_CRATE_NAME")).into()),23        )24        .with(tracing_subscriber::fmt::layer())25        .init();2627    // build our application with some routes28    let app = app();2930    // run it31    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")32        .await33        .unwrap();34    tracing::debug!("listening on {}", listener.local_addr().unwrap());35    axum::serve(listener, app).await;36}3738fn app() -> Router {39    Router::new().route("/{version}/foo", get(handler))40}4142async fn handler(version: Version) -> Html<String> {43    Html(format!("received request with version {version:?}"))44}4546#[derive(Debug)]47enum Version {48    V1,49    V2,50    V3,51}5253impl<S> FromRequestParts<S> for Version54where55    S: Send + Sync,56{57    type Rejection = Response;5859    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {60        let params: Path<HashMap<String, String>> =61            parts.extract().await.map_err(IntoResponse::into_response)?;6263        let version = params64            .get("version")65            .ok_or_else(|| (StatusCode::NOT_FOUND, "version param missing").into_response())?;6667        match version.as_str() {68            "v1" => Ok(Version::V1),69            "v2" => Ok(Version::V2),70            "v3" => Ok(Version::V3),71            _ => Err((StatusCode::NOT_FOUND, "unknown version").into_response()),72        }73    }74}7576#[cfg(test)]77mod tests {78    use super::*;79    use axum::{body::Body, http::Request, http::StatusCode};80    use http_body_util::BodyExt;81    use tower::ServiceExt;8283    #[tokio::test]84    async fn test_v1() {85        let response = app()86            .oneshot(Request::get("/v1/foo").body(Body::empty()).unwrap())87            .await88            .unwrap();8990        assert_eq!(response.status(), StatusCode::OK);91        let body = response.into_body();92        let bytes = body.collect().await.unwrap().to_bytes();93        let html = String::from_utf8(bytes.to_vec()).unwrap();9495        assert_eq!(html, "received request with version V1");96    }9798    #[tokio::test]99    async fn test_v4() {100        let response = app()101            .oneshot(Request::get("/v4/foo").body(Body::empty()).unwrap())102            .await103            .unwrap();104105        assert_eq!(response.status(), StatusCode::NOT_FOUND);106        let body = response.into_body();107        let bytes = body.collect().await.unwrap().to_bytes();108        let html = String::from_utf8(bytes.to_vec()).unwrap();109110        assert_eq!(html, "unknown version");111    }112}