Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Custom response struct

[package]
name = "custom-respons-struct"
version = "0.1.0"
edition = "2024"
publish = false

[dependencies]
axum = "0.8.8"
tokio = { version = "1.50.0", features = ["full"] }

[dev-dependencies]
http-body-util = "0.1.0"
tower = { version = "0.5.2", features = ["util"] }

Code

use axum::{
    Router,
    http::StatusCode,
    http::header,
    response::{Html, IntoResponse, Response},
    routing::get,
};

struct OurMessage<'a> {
    text: String,
    lang: &'a str,
}

// Tell axum how to convert `OurMessage` into a response.
impl IntoResponse for OurMessage<'_> {
    fn into_response(self) -> Response {
        (
            StatusCode::OK,
            [(header::CONTENT_TYPE, "text/html; charset=utf-8")],
            format!("Text: {} in language: {}", self.text, self.lang),
        )
            .into_response()
    }
}

async fn main_page() -> Html<&'static str> {
    Html(
        r#"<h1>Main page</h1>
    <a href="/english">English</a><br>
    <a href="/hungarian">Hungarian</a><br>
        "#,
    )
}

async fn english_page() -> impl IntoResponse {
    OurMessage {
        text: String::from("Some text comes here"),
        lang: "en",
    }
}

async fn hungarian_page() -> impl IntoResponse {
    OurMessage {
        text: String::from("Magyarul is lehet"),
        lang: "hu",
    }
}

fn create_router() -> Router {
    Router::new()
        .route("/", get(main_page))
        .route("/english", get(english_page))
        .route("/hungarian", get(hungarian_page))
}

#[tokio::main]
async fn main() {
    let app = create_router();

    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("listening on {}", listener.local_addr().unwrap());
    axum::serve(listener, app).await.unwrap();
}

#[cfg(test)]
mod tests;

Tests

#![allow(unused)]
fn main() {
use super::*;
use axum::{body::Body, http::Request, http::StatusCode};
use http_body_util::BodyExt;
use tower::ServiceExt;

#[tokio::test]
async fn test_main_page() {
    let response = create_router()
        .oneshot(Request::get("/").body(Body::empty()).unwrap())
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::OK);

    let content_type = response.headers().get("content-type").unwrap();
    assert_eq!(content_type.to_str().unwrap(), "text/html; charset=utf-8");

    let body = response.into_body();
    let bytes = body.collect().await.unwrap().to_bytes();
    let html = String::from_utf8(bytes.to_vec()).unwrap();

    assert!(html.contains("<h1>Main page</h1>"));
}

#[tokio::test]
async fn test_english() {
    let response = create_router()
        .oneshot(Request::get("/english").body(Body::empty()).unwrap())
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::OK);

    let content_type = response.headers().get("content-type").unwrap();
    assert_eq!(content_type.to_str().unwrap(), "text/html; charset=utf-8");

    let body = response.into_body();
    let bytes = body.collect().await.unwrap().to_bytes();
    let html = String::from_utf8(bytes.to_vec()).unwrap();

    assert_eq!(html, "Text: Some text comes here in language: en");
}

#[tokio::test]
async fn test_hungarian() {
    let response = create_router()
        .oneshot(Request::get("/hungarian").body(Body::empty()).unwrap())
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::OK);

    let content_type = response.headers().get("content-type").unwrap();
    assert_eq!(content_type.to_str().unwrap(), "text/html; charset=utf-8");

    let body = response.into_body();
    let bytes = body.collect().await.unwrap().to_bytes();
    let html = String::from_utf8(bytes.to_vec()).unwrap();

    assert_eq!(html, "Text: Magyarul is lehet in language: hu");
}
}