use std::{
collections::HashMap,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
};
use crate::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("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(200, "OK".into())
.body_and_auto_content_headers(HttpBody::Json(res_json))
.build(),
)
});
let stop_flag = Arc::new(AtomicBool::new(false));
let handle = router.thread_start_at_port(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": "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();
}