Skip to content

Instantly share code, notes, and snippets.

@martinsk
Created July 11, 2023 00:54
Show Gist options
  • Save martinsk/5c5f06d3b13abadc7eb2adecfae4375d to your computer and use it in GitHub Desktop.
Save martinsk/5c5f06d3b13abadc7eb2adecfae4375d to your computer and use it in GitHub Desktop.
Rust webserver
use http_body_util::Full;
use hyper::server::conn::http1;
use hyper::{body::Bytes, service::service_fn, Request, Response};
use std::{convert::Infallible, error::Error, net::SocketAddr};
use tokio::net::TcpListener;
async fn hello(_: Request<hyper::body::Incoming>) -> Result<Response<Full<Bytes>>, Infallible> {
Ok(Response::new(Full::new(Bytes::from("Hello World!"))))
}
fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
tokio::runtime::Builder::new_current_thread()
.worker_threads(1)
.enable_io()
.build()
.unwrap()
.block_on(tokio_main())
}
async fn tokio_main() -> Result<(), Box<dyn Error + Send + Sync>> {
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
let listener = TcpListener::bind(addr).await?;
loop {
let (stream, _) = listener.accept().await?;
tokio::task::spawn(async move {
if let Err(err) = http1::Builder::new()
.serve_connection(stream, service_fn(hello))
.await
{
println!("Error serving connection: {:?}", err);
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment