-
-
Save martinsk/5c5f06d3b13abadc7eb2adecfae4375d to your computer and use it in GitHub Desktop.
Rust webserver
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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