yan_net 0.2.1

A simple library for sending HTTP requests and creating HTTP servers
Documentation
use std::{
    collections::HashMap,
    sync::{
        Arc,
        atomic::{AtomicBool, Ordering},
    },
};

use serial_test::serial;

use crate::prelude::*;
use yan_json::prelude::*;

#[test]
#[serial]
fn client() {
    let req = RequestBuilder::new()
        .method(HttpMethod::Get)
        .path("/posts/0")
        .header("Host", "json-placeholder.mock.beeceptor.com:80")
        .body_and_auto_content_headers(HttpBody::None)
        .build();

    let res = req.send().unwrap();
    println!("request recieved: {:#?}", res);

    let res_json_expected = json!({
        "userId": 1,
        "id": 0,
        "title": "Introduction to Artificial Intelligence",
        "body": "Learn the basics of Artificial Intelligence and its applications in various industries.",
        "link": "https://example.com/article1",
        "comment_count": 8
    });

    assert_eq!(res.body.as_json(), Some(&res_json_expected));
}

#[test]
#[serial]
fn server() {
    let mut server = Server::new();
    server.map("/api/echo", HttpMethod::Post, |req| {
        let req_json: JsonNode = req.body.try_into().ok()?;
        let req_json_obj = req_json.as_obj()?;
        let data_in = req_json_obj.get("data")?.as_str()?;
        let count = req_json_obj.get("count")?.as_f64()? as usize;
        let buffer = req_json_obj.get("sep")?.as_str()?;

        let data_out: &str = &vec![data_in; count].join(buffer);
        let res_json = json!({
            "result": data_out
        });

        println!("{res_json}");

        Some(
            ResponseBuilder::new()
                .status_ok()
                .body_and_auto_content_headers(HttpBody::Json(res_json))
                .build(),
        )
    });

    let stop_flag = Arc::new(AtomicBool::new(false));
    let handle = server.thread_start_at_port(8000, stop_flag.clone());

    let req = RequestBuilder::new()
        .method(HttpMethod::Post)
        .path("/api/echo")
        .header("Host", "127.0.0.1:8000")
        .body_and_auto_content_headers(HttpBody::Json(json!({
                    "data": "abc",
                    "count": 3,
                    "sep": ":=:"
        })))
        .build();
    let res = req.send().unwrap();
    println!("recieved: {:#?}", res);

    assert_eq!(
        res.body.as_json(),
        Some(&json!({
            "result": "abc:=:abc:=:abc"
        }))
    );

    stop_flag.store(true, Ordering::SeqCst);
    handle.join().unwrap();
}

#[test]
#[serial]
fn server_static() {
    let mut server = Server::new();
    server.mount_static("/files", "static_files/");

    let stop_flag = Arc::new(AtomicBool::new(false));
    let handle = server.thread_start_at_port(8000, stop_flag.clone());

    // build the request
    let req = RequestBuilder::new()
        .method(HttpMethod::Get)
        .path("/files")
        .header("Host", "127.0.0.1:8000")
        .body_and_auto_content_headers(HttpBody::None)
        .build();

    // send the request you just build and save the response
    let res = req.send().unwrap();

    // make sure the response matches index.html in static_files/
    assert_eq!(
        res.body,
        HttpBody::Html(
            r#"<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <p>This is static_files/index.html</p>
</body>
</html>
"#
            .to_string()
        )
    );

    stop_flag.store(true, Ordering::SeqCst);
    handle.join().unwrap();
}