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
|
use hyper::service::{make_service_fn, service_fn};
use hyper::{Body, Method, Request, Response, Server, StatusCode};
use sha2::{Sha256, Digest};
use std::io::Write;
/// This is our service handler. It receives a Request, routes on its
/// path, and returns a Future of a Response.
async fn echo(req: Request<Body>) -> Result<Response<Body>, hyper::Error> {
match (req.method(), req.uri().path()) {
// Serve some instructions at /
(&Method::GET, "/") => Ok(Response::new(Body::from(
"Try POSTing data to /echo such as: `curl localhost:8000/echo -XPOST -d 'hello world'`",
))),
// Simply echo the body back to the client.
(&Method::POST, "/echo") => Ok(Response::new(req.into_body())),
(&Method::POST, "/survey") => {
let full_body = hyper::body::to_bytes(req.into_body()).await?;
let mut hasher = Sha256::new();
hasher.update(full_body.clone());
let hash = hasher.finalize();
let mut file = std::fs::File::create(
format!("answers-{}.age", hex::encode(hash))
).unwrap();
file.write_all(&full_body).unwrap();
println!("got hash: {:?}", hash);
Ok(Response::new(
"thanks for hading in these answers!".into()
))
}
// Return the 404 Not Found for other routes.
_ => {
Ok(Response::builder()
.status(StatusCode::NOT_FOUND)
.body("nothing here!\n".into())
.unwrap()
)
}
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let addr = ([127, 0, 0, 1], 8000).into();
let service = make_service_fn(
|_| async {
Ok::<_, hyper::Error>(service_fn(echo))
}
);
let server = Server::bind(&addr).serve(service);
println!("Listening on http://{}", addr);
server.await?;
Ok(())
}
|