Skip to content

Instantly share code, notes, and snippets.

@panicbit
Created May 8, 2020 17:49
Show Gist options
  • Save panicbit/dff1a2253e45887a677879dd992012b7 to your computer and use it in GitHub Desktop.
Save panicbit/dff1a2253e45887a677879dd992012b7 to your computer and use it in GitHub Desktop.
use std::convert::Infallible;
use std::{error::Error, net::SocketAddr, time::{Instant, Duration}};
use hyper::{Body, Request, Response, Server};
use hyper::{body::Bytes, service::{make_service_fn, service_fn}};
use futures::prelude::*;
use tokio::time::delay_for;
#[tokio::main]
async fn main() {
let addr = SocketAddr::from(([0, 0, 0, 0], 7777));
let make_service = make_service_fn(|_conn| async {
Ok::<_, Infallible>(service_fn(handle))
});
let server = Server::bind(&addr).serve(make_service);
if let Err(e) = server.await {
eprintln!("server error: {}", e);
}
}
async fn handle(req: Request<Body>) -> Result<Response<Body>, Infallible> {
let start = Instant::now();
println!("request: {:?}", req);
let stream = stream::unfold((), move |_| async move {
println!("Alive after {:.0?}", start.elapsed());
delay_for(Duration::from_secs(1)).await;
let bytes = Bytes::from_static(b" ");
Some((Ok::<_, Box<dyn Error + Send + Sync + 'static>>(bytes), ()))
});
let body = Body::wrap_stream(stream);
Ok(Response::new(body))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment