yan_net 0.1.0

A simple library for sending HTTP requests and creating HTTP servers
Documentation
use std::{
    collections::HashMap,
    sync::{Arc, Mutex, RwLock},
    time::Duration,
};

use crate::{http::RequestBuilder, prelude::*};
use yan_json::prelude::*;

#[test]
fn client() {
    let req = RequestBuilder::new()
        .method(HttpMethod::Get)
        .path("/posts/0".to_string())
        .header(
            "Host".to_string(),
            "json-placeholder.mock.beeceptor.com:80".to_string(),
        )
        .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]
fn server() {
    let mut router: RouteMapper = RouteMapper::new();
    router.map("/api/echo".into(), 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("buffer")?.as_str()?;

        let data_out = vec![data_in; count].join(buffer);

        let res_json = JsonNode::Object(HashMap::from([(
            "result".into(),
            JsonNode::String(data_out),
        )]));

        println!("{res_json}");

        Some(
            ResponseBuilder::new()
                .status(200, "OK".into())
                .body_and_auto_content_headers(HttpBody::Json(res_json))
                .build(),
        )
    });

    let stop_flag = Arc::new(RwLock::new(false));
    RouteMapper::thread_start_at_port(router, 8000, stop_flag.clone());

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

    assert_eq!(
        res.body.as_json(),
        Some(&json!({
            "result": "this is some data :=: this is some data :=: this is some data"
        }))
    );

    *stop_flag.write().unwrap() = true;
}