diff options
Diffstat (limited to '')
-rw-r--r-- | server/src/main.rs | 64 |
1 files changed, 64 insertions, 0 deletions
diff --git a/server/src/main.rs b/server/src/main.rs new file mode 100644 index 0000000..ec2c77c --- /dev/null +++ b/server/src/main.rs @@ -0,0 +1,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(()) +} |