create a http server and add a custom header to the response in rust

To create an HTTP server in Rust, we can use the hyper crate, which provides a low-level HTTP implementation. Here's an example of how to create a minimal HTTP server that returns a "Hello World" response with a custom header:

main.rs
use hyper::{Body, Request, Response, Server};
use hyper::header::{HeaderValue, CONTENT_TYPE};

async fn hello_world(_: Request<Body>) -> Result<Response<Body>, hyper::Error> {
    let mut response = Response::new(Body::from("Hello World"));
    response.headers_mut().insert(CONTENT_TYPE, HeaderValue::from_static("text/plain"));
    response.headers_mut().insert("X-Custom-Header", HeaderValue::from_static("Hello from Rust!"));
    Ok(response)
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let addr = ([127, 0, 0, 1], 3000).into();
    let service = hyper::service::make_service_fn(|_| async {
        Ok::<_, hyper::Error>(hyper::service::service_fn(hello_world))
    });
    let server = Server::bind(&addr).serve(service);
    println!("Listening on http://{}", addr);
    server.await?;
    Ok(())
}
857 chars
22 lines

In this example, we define a function called hello_world that takes a Request and returns a Response. We create a new Response with the Body "Hello World", set the "Content-Type" header to "text/plain", and add a custom header called "X-Custom-Header" with the value "Hello from Rust!".

We then use make_service_fn to create a new service for each incoming connection. This service is created by calling service_fn with our hello_world function as the handler.

Finally, we create a new Server instance by calling bind with the socket address we want to listen on, and passing in our service. We can then call await on the server to start listening for incoming connections and serving our responses.

With this example, we have demonstrated how to create a minimal HTTP server in Rust and add a custom header to the response.

gistlibby LogSnag