Skip to content
Myr

main.rs

This file

Path

examples/handle-head-request/src/main.rs

81 lines · 2.2 KiB · Rust

Last changed by

Fix return types of serve futures (#3601)Jonas Plattebefore adoptionf3a95d7

History of this file

Take it

1//! Run with2//!3//! ```not_rust4//! cargo run -p example-handle-head-request5//! ```67use axum::response::{IntoResponse, Response};8use axum::{http, routing::get, Router};910fn app() -> Router {11    Router::new().route("/get-head", get(get_head_handler))12}1314#[tokio::main]15async fn main() {16    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")17        .await18        .unwrap();19    println!("listening on {}", listener.local_addr().unwrap());20    axum::serve(listener, app()).await;21}2223// GET routes will also be called for HEAD requests but will have the response body removed.24// You can handle the HEAD method explicitly by extracting `http::Method` from the request.25async fn get_head_handler(method: http::Method) -> Response {26    // it usually only makes sense to special-case HEAD27    // if computing the body has some relevant cost28    if method == http::Method::HEAD {29        return ([("x-some-header", "header from HEAD")]).into_response();30    }3132    // then do some computing task in GET33    do_some_computing_task();3435    ([("x-some-header", "header from GET")], "body from GET").into_response()36}3738fn do_some_computing_task() {39    // TODO40}4142#[cfg(test)]43mod tests {44    use super::*;45    use axum::body::Body;46    use axum::http::{Request, StatusCode};47    use http_body_util::BodyExt;48    use tower::ServiceExt;4950    #[tokio::test]51    async fn test_get() {52        let app = app();5354        let response = app55            .oneshot(Request::get("/get-head").body(Body::empty()).unwrap())56            .await57            .unwrap();5859        assert_eq!(response.status(), StatusCode::OK);60        assert_eq!(response.headers()["x-some-header"], "header from GET");6162        let body = response.collect().await.unwrap().to_bytes();63        assert_eq!(&body[..], b"body from GET");64    }6566    #[tokio::test]67    async fn test_implicit_head() {68        let app = app();6970        let response = app71            .oneshot(Request::head("/get-head").body(Body::empty()).unwrap())72            .await73            .unwrap();7475        assert_eq!(response.status(), StatusCode::OK);76        assert_eq!(response.headers()["x-some-header"], "header from HEAD");7778        let body = response.collect().await.unwrap().to_bytes();79        assert!(body.is_empty());80    }81}