use std::convert::Infallible;
use hyper::service;
use hyper::{Body, Request, Response, Server};

async fn hello(request: Request<Body>) -> Result<Response<Body>, Infallible> {
    let mut buff = String::with_capacity(1024);
    buff.push_str(&request.method().to_string());
    buff.push(' ');
    buff.push_str(&request.uri().to_string());
    buff.push(' ');
    buff.push_str(&format!("{:?}", request.version().to_owned()));
    buff.push('\n');
    for header in  request.headers() {
        buff.push_str(&header.0.to_string());
        buff.push_str(": ");
        buff.push_str(header.1.to_str().unwrap_or_else(|_| "<to_string_error>"));
        buff.push('\n');
    }
    Ok(Response::new(Body::from(buff)))
}

// https://github.com/hyperium/hyper/blob/master/examples/hello.rs
#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    // For every connection, we must make a `Service` to handle all
    // incoming HTTP requests on said connection.
    let make_svc = service::make_service_fn(|_conn| {
        // This is the `Service` that will handle the connection.
        // `service_fn` is a helper to convert a function that
        // returns a Response into a `Service`.
        async { Ok::<_, Infallible>(service::service_fn(hello)) }
    });

    let addr = ([0, 0, 0, 0], 9000).into();
    let server = Server::bind(&addr).serve(make_svc);
    println!("Listening on http://{}", addr);

    server.await?;
    Ok(())
}