return a html response from a http server in rust

To return a HTML response from a HTTP server in Rust, you can use the hyper crate as follows:

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

async fn handle_request(_req: Request<Body>) -> Result<Response<Body>, hyper::Error> {
    let html_content = "<html><body><h1>Hello, world!</h1></body></html>".to_string();
    Ok(Response::new(Body::from(html_content)))
}

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

    println!("Listening on http://{}", addr);

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

In this example, we bind a Server to a socket address (localhost:8080). The server's make_service_fn function creates a new instance of a service on each incoming connection, and sets it up to serve this request. This service function (handle_request) takes a request and returns a Result with a Response that contains the HTML content.

The tokio::main macro is used here to initiate an asynchronous runtime and run the server.

related categories

gistlibby LogSnag