1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// TODO: Finish this example.
// use serde::Deserialize;
// use serde_json::json;
// use servlin::reexport::{safina_executor, safina_timer};
// use servlin::{print_log_response, socket_addr_127_0_0_1, HttpServerBuilder, Request, Response};
// use std::io::Read;
// use std::sync::atomic::{AtomicUsize, Ordering};
// use std::sync::Arc;
// use temp_dir::TempDir;
//
// pub struct State {
// upload_count: AtomicUsize,
// }
//
// fn upload(state: &Arc<State>, req: &Request) -> Result<Response, Response> {
// if req.body.is_pending() {
// println!("continue");
// return Ok(Response::get_body_and_reprocess(1024 * 1024));
// }
// println!("upload receiving");
// let mut body_string = String::new();
// req.body.reader()?.read_to_string(&mut body_string)?;
// //dbg!(&body_string);
// state.upload_count.fetch_add(1, Ordering::AcqRel);
// Ok(Response::text(
// 200,
// format!(
// "Upload received, body_len={}, upload_count={}\n",
// body_string.len(),
// state.upload_count.load(Ordering::Acquire)
// ),
// ))
// }
//
// fn hello(req: &Request) -> Result<Response, Response> {
// #[derive(Deserialize)]
// struct Input {
// name: String,
// }
// let input: Input = req.json()?;
// Ok(Response::json(
// 200,
// json!({ "message": format!("Helle, {}! Nice to meet you.", input.name) }),
// )
// .unwrap())
// }
//
// async fn handle_req(
// state: &Arc<State>,
// http_conn: &mut HttpConn,
// mut req: Request,
// ) -> Result<Response, HttpError> {
// let blocking = |f| async {
// with_timeout(schedule_blocking(f).async_recv(), Duration::from_secs(10)).await??
// };
// match (req.method(), req.url().path()) {
// ("GET", "/ping") => Ok(Response::text(200, "ok")),
// ("POST", "/hello") => blocking(|| hello(req)).await?,
// ("GET", "/events") => blocking(|| events(req, state)).await?,
// ("POST", "/upload") => {
// if req.body.is_pending() {
// blocking(|| check_upload(state.clone(), req.clone())).await?;
// req.body = with_timeout(
// http_conn.read_body_to_file(cache_dir.path(), 1024 * 1024),
// Duration::from_secs(120),
// )
// .await??;
// }
// blocking(|| handle_upload(state, req)).await?
// }
// _ => Ok(Response::text(404, "Not found")),
// }
// }
// let handler = move |http_conn: &mut HttpConn| {
// let mut req = http_conn.read_request().await?;
// print_logger(&req).log(handle_req(&state, http_conn, req).await)
// };