create a http server in rust

To create an HTTP server in Rust, we can use the hyper library. Here's an example of a simple HTTP server using hyper:

main.rs
use hyper::{Body, Request, Response, Server};
use std::net::SocketAddr;

async fn handle_request(_req: Request<Body>) -> Result<Response<Body>, hyper::Error> {
    Ok(Response::new(Body::from("Hello, World!")))
}

#[tokio::main]
async fn main() {
    let addr = SocketAddr::from(([127, 0, 0, 1], 8080));
    let service = hyper::service::make_service_fn(|_conn| async {
        Ok::<_, hyper::Error>(hyper::service::service_fn(handle_request))
    });

    let server = Server::bind(&addr).serve(service);
    println!("Listening on http://{}", addr);

    if let Err(e) = server.await {
        eprintln!("server error: {}", e);
    }
}
638 chars
22 lines

Here, we define a handle_request function to handle incoming requests. This function simply returns a Response with the body "Hello, World!".

We then define a main function, which creates a SocketAddr to bind the server to, and a service that uses make_service_fn to create a new service on each incoming connection.

Finally, we create the Server and call await on it to listen for and handle incoming connections.

You can run this code with cargo run, and then navigate to http://localhost:8080 in your browser to see the "Hello, World!" response.

gistlibby LogSnag