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

Logging to a file

[package]
name = "echo-post"
version = "0.1.0"
edition = "2024"
publish = false

[dependencies]
axum = "0.8.8"
mime = "0.3.17"
serde = { version = "1.0.228", features = ["derive"] }
tokio = { version = "1.50.0", features = ["full"] }
chrono = "0.4.42"
tracing = "0.1.41"
tracing-subscriber = "0.3.20"


[dev-dependencies]
headers = "0.4.1"
http-body-util = "0.1.3"
tower = { version = "0.5.3", features = ["util"] }
use tracing_subscriber::{
    Layer, filter::LevelFilter, layer::SubscriberExt, util::SubscriberInitExt,
};

use axum::{
    Form, Router,
    response::Html,
    routing::{get, post},
};
use serde::Deserialize;

#[derive(Debug, Deserialize)]
#[allow(dead_code)]
struct Params {
    text: String,
}

async fn main_page() -> Html<&'static str> {
    tracing::info!("main page");
    Html(
        r#"
    <form method="post" action="/echo">
    <input type="text" name="text">
    <input type="submit" value="Echo">
    </form>
    "#,
    )
}

async fn echo(Form(params): Form<Params>) -> Html<String> {
    tracing::info!("params: {:?}", params);
    Html(format!(r#"You said: <b>{}</b>"#, params.text))
}

fn create_router() -> Router {
    Router::new()
        .route("/", get(main_page))
        .route("/echo", post(echo))
}

#[tokio::main]
async fn main() {
    setup_tracing("demo");
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("listening on {}", listener.local_addr().unwrap());
    axum::serve(listener, create_router()).await.unwrap();
}

fn setup_tracing(prefix: &str) {
    let date = chrono::Local::now().format("%Y-%m-%d").to_string();
    std::fs::create_dir_all("logs").unwrap();
    let log_filename = format!("logs/{}-{}.log", prefix, date);

    tracing_subscriber::registry()
        .with(
            tracing_subscriber::fmt::layer()
                .with_ansi(false)
                .with_writer(
                    std::fs::OpenOptions::new()
                        .create(true)
                        .append(true)
                        .open(log_filename)
                        .unwrap(),
                )
                .with_filter(LevelFilter::DEBUG),
        )
        .with(tracing_subscriber::fmt::layer())
        .init();
}
#[cfg(test)]
mod tests;
#![allow(unused)]
fn main() {
use super::*;
use axum::{
    body::Body,
    http::{self, Request, StatusCode},
};
use http_body_util::BodyExt;
use tower::ServiceExt;

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

    assert_eq!(response.status(), StatusCode::OK);
    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(r#"<form method="post" action="/echo">"#));
}

#[tokio::test]
async fn test_echo_with_data() {
    let response = create_router()
        .oneshot(
            Request::builder()
                .method(http::Method::POST)
                .uri("/echo")
                .header(
                    http::header::CONTENT_TYPE,
                    mime::APPLICATION_WWW_FORM_URLENCODED.as_ref(),
                )
                .body(Body::from("text=Hello+World!"))
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::OK);
    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, "You said: <b>Hello World!</b>");
}

#[tokio::test]
async fn test_echo_without_data() {
    let response = create_router()
        .oneshot(
            Request::builder()
                .method(http::Method::POST)
                .uri("/echo")
                .header(
                    http::header::CONTENT_TYPE,
                    mime::APPLICATION_WWW_FORM_URLENCODED.as_ref(),
                )
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY); // 422
    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,
        "Failed to deserialize form body: missing field `text`"
    );
}

#[tokio::test]
async fn test_echo_missing_value() {
    let response = create_router()
        .oneshot(
            Request::builder()
                .method(http::Method::POST)
                .uri("/echo")
                .header(
                    http::header::CONTENT_TYPE,
                    mime::APPLICATION_WWW_FORM_URLENCODED.as_ref(),
                )
                .body(Body::from("text="))
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::OK);
    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, "You said: <b></b>");
}

#[tokio::test]
async fn test_echo_extra_param() {
    let response = create_router()
        .oneshot(
            Request::builder()
                .method(http::Method::POST)
                .uri("/echo")
                .header(
                    http::header::CONTENT_TYPE,
                    mime::APPLICATION_WWW_FORM_URLENCODED.as_ref(),
                )
                .body(Body::from("text=Hello&extra=123"))
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::OK);
    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, "You said: <b>Hello</b>");
}
}