Post

Simple HTTP Server in Rust

Here’s an example of an HTTP server in Rust that uses the std::net and std::io libraries:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
use std::net::{TcpListener, TcpStream};
use std::io::{Read, Write};
use std::thread;

fn main() {
    let listener = TcpListener::bind("127.0.0.1:3000").unwrap();

    for stream in listener.incoming() {
        let stream = stream.unwrap();

        thread::spawn(|| {
            handle_connection(stream);
        });
    }
}

fn handle_connection(mut stream: TcpStream) {
    let mut buffer = [0; 512];
    stream.read(&mut buffer).unwrap();

    let response = "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 12\r\n\r\nHello, World!";

    stream.write(response.as_bytes()).unwrap();
    stream.flush().unwrap();
}

This server listens on http://127.0.0.1:3000, and responds to all requests with a 200 OK response with a body of “Hello, World!”.

To run this server, you don’t need to add any additional dependencies to your Cargo.toml file. You should be able to build and run the server with cargo run.

This post is licensed under CC BY 4.0 by the author.