| #[macro_use] | |
| extern crate log; | |
| extern crate env_logger; | |
| extern crate futures; | |
| extern crate hyper; | |
| extern crate url; | |
| use hyper::{ | |
| Body, | |
| Chunk, | |
| Request, | |
| Response, | |
| Method, | |
| Server, | |
| StatusCode | |
| }; | |
| use hyper::service::service_fn; | |
| use futures::{future, Future, Stream}; | |
| use std::io; | |
| use std::collections::HashMap; | |
| struct NewMessage { | |
| username: String, | |
| message: String, | |
| } | |
| fn parse_form(form_chunk: Chunk) -> future::FutureResult<NewMessage, hyper::Error> { | |
| let mut form: HashMap<String, String> = url::form_urlencoded::parse(form_chunk.as_ref()) | |
| .into_owned() | |
| .collect(); | |
| if let Some(message) = form.remove("message") { | |
| let username = form.remove("username").unwrap_or(String::from("anonymous")); | |
| future::ok(NewMessage { | |
| username, | |
| message, | |
| }) | |
| } else { | |
| future::err(hyper::Error::from(io::Error::new( | |
| io::ErrorKind::InvalidInput, | |
| "Missing field `message`", | |
| ))) | |
| } | |
| } | |
| fn write_to_db(_entry: NewMessage) -> future::FutureResult<i64, hyper::Error> { | |
| future::ok(0) | |
| } | |
| fn make_post_response( | |
| _result: Result<i64, hyper::Error> | |
| ) -> future::FutureResult<Response<Body>, hyper::Error> { | |
| future::ok(Response::builder() | |
| .status(StatusCode::NOT_FOUND) | |
| .body(Body::empty()) | |
| .unwrap()) | |
| } | |
| fn router(req: Request<Body>) -> Box<Future<Item=Response<Body>, Error=hyper::Error> + Send> { | |
| info!("Microservice received a request: {:?}", req); | |
| match (req.method(), req.uri().path()) { | |
| (&Method::POST, "/") => { | |
| let fut = req.into_body() | |
| .concat2() | |
| .and_then(parse_form) | |
| .and_then(write_to_db) | |
| .then(make_post_response); | |
| Box::new(fut) | |
| } | |
| _ => Box::new(future::ok( | |
| Response::builder() | |
| .status(StatusCode::NOT_FOUND) | |
| .body(Body::empty()) | |
| .unwrap() | |
| )), | |
| } | |
| } | |
| fn main() { | |
| env_logger::init(); | |
| let addr = ([127, 0, 0, 1], 3000).into(); | |
| let server = Server::bind(&addr) | |
| .serve(|| service_fn(router)) | |
| .map_err(|e| eprintln!("server error: {}", e)); | |
| info!("Running server on {}", addr); | |
| hyper::rt::run(server); | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment