Creating a Basic HTTP Server in Rust using Hyper: A Step-by-Step Tutorial

Ajay Bhatia
2 min readNov 8, 2023

--

Introduction

In this tutorial, we’ll walk through the process of building a basic HTTP server using Rust programming language and the Hyper crate. Hyper is a fast and robust HTTP library in Rust that allows us to create high-performance web servers.

Prerequisites

Before we start, ensure you have Rust installed. You can install Rust by following the instructions on Rust’s official website. Additionally, make sure you have a code editor installed (such as VS Code or IntelliJ IDEA).

Step 1: Setting up a new Rust project

Let’s create a new Rust project using Cargo, Rust’s package manager. Open your terminal and run the following commands:

cargo new rust_http_server
cd rust_http_server

This will create a new directory named rust_http_server and initialize a new Rust project within it.

Step 2: Adding Hyper as a dependency

Open the Cargo.toml file in your project directory and add the Hyper dependency to it:

[dependencies]
hyper = "0.14"

Save the Cargo.toml file. Cargo will manage the installation of the Hyper crate when you build the project.

Step 3: Writing the HTTP server code

Next, create a file named main.rs in the src directory of your project. Add the following code to create a basic HTTP server using Hyper:

use hyper::{Body, Request, Response, Server};
use hyper::service::{make_service_fn, service_fn};
use std::convert::Infallible;

async fn handle_request(_req: Request<Body>) -> Result<Response<Body>, Infallible> {
// Process the incoming request here
// For this example, we'll just return a simple response
Ok(Response::new(Body::from("Hello, Rust HTTP Server!")))
}

#[tokio::main]
async fn main() {
let make_svc = make_service_fn(|_conn| {
async {
Ok::<_, Infallible>(service_fn(handle_request))
}
});

let addr = ([127, 0, 0, 1], 3000).into();
let server = Server::bind(&addr).serve(make_svc);

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

Step 4: Running the server

To run the server, go back to your terminal, navigate to the project’s root directory, and run the following command:

cargo run

This will compile the code and start your Rust HTTP server. The server will be accessible at http://127.0.0.1:3000.

Conclusion

Congratulations! You’ve successfully created a basic HTTP server in Rust using the Hyper crate. This server listens on port 3000 and responds with a “Hello, Rust HTTP Server!” message to incoming requests. You can extend this server by handling different routes, parsing request data, and integrating various features as needed.

This tutorial provides a foundation for creating web servers in Rust. Explore the Hyper crate’s documentation and Rust’s capabilities to further enhance and expand your server based on your project’s requirements.

Feel free to modify and extend the server code to suit your specific use cases.

--

--