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:
We define two handler functions:
helloandheaders. These are asynchronous functions that return a type implementing theRespondertrait.The
hellofunction simply returns the string “hello\n”.The
headersfunction reads all the HTTP request headers and echoes them into the response body.In the
mainfunction, we set up the server usingHttpServer::new(). We define the routes for our handlers using theroutemethod.Finally, we bind the server to the address “127.0.0.1:8090” and run it.
To run the server:
$ cargo runYou can then access the server using curl:
$ curl localhost:8090/hello
helloThis 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.