Http Server in Rust

Here’s the translation of the HTTP server example from Go to Rust:

Our first HTTP server example demonstrates how to create a basic server using the actix-web crate.

use actix_web::{web, App, HttpRequest, HttpServer, Responder};

// A simple handler that returns "hello\n"
async fn hello() -> impl Responder {
    "hello\n"
}

// A handler that echoes the request headers
async fn headers(req: HttpRequest) -> impl Responder {
    let mut response = String::new();
    for (name, value) in req.headers() {
        response.push_str(&format!("{}: {:?}\n", name, value));
    }
    response
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    // Start the HTTP server
    HttpServer::new(|| {
        App::new()
            .route("/hello", web::get().to(hello))
            .route("/headers", web::get().to(headers))
    })
    .bind("127.0.0.1:8090")?
    .run()
    .await
}

In this Rust example, we’re using the actix-web framework to create an HTTP server. Here’s a breakdown of the code:

  1. We define two handler functions: hello and headers. These are asynchronous functions that return a type implementing the Responder trait.

  2. The hello function simply returns the string “hello\n”.

  3. The headers function reads all the HTTP request headers and echoes them into the response body.

  4. In the main function, we set up the server using HttpServer::new(). We define the routes for our handlers using the route method.

  5. Finally, we bind the server to the address “127.0.0.1:8090” and run it.

To run the server:

$ cargo run

You can then access the server using curl:

$ curl localhost:8090/hello
hello

This example demonstrates how to create a basic HTTP server in Rust, handle different routes, and work with request headers. The actix-web framework provides a lot of functionality out of the box, making it easy to create robust web services.

Next, we’ll explore more advanced concepts in Rust web development.