create a http server with a get route in rust

Here's an example on how to create a simple HTTP server that listens on port 8080 and handles GET requests on the root path ("/"):

main.rs
use std::io::prelude::*;
use std::net::TcpListener;
use std::net::TcpStream;

fn handle_client(mut stream: TcpStream) {
    let response = "HTTP/1.1 200 OK\r\n\r\nHello, World!";
    stream.write(response.as_bytes()).unwrap();
    stream.flush().unwrap();
}

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

    for stream in listener.incoming() {
        match stream {
            Ok(stream) => {
                std::thread::spawn(|| {
                    handle_client(stream)
                });
            }
            Err(e) => { println!("{:?}", e) }
        }
    }

    drop(listener);
}
629 chars
27 lines

This code listens for incoming TCP connections on "127.0.0.1:8080". When a connection is established, a new thread is created to handle the connection. The handle_client() function writes a simple HTTP response back to the client, in this case just the Hello, World! string.

To add a route to the server, you can inspect the incoming request and dispatch the handling to different functions based on the requested path. Here's an example that matches the root path ("/") and returns a JSON response:

main.rs
use std::io::prelude::*;
use std::net::TcpListener;
use std::net::TcpStream;

fn handle_root(mut stream: TcpStream) {
    let response = "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\r\n{\"message\": \"Hello, World!\"}";
    stream.write(response.as_bytes()).unwrap();
    stream.flush().unwrap();
}

fn handle_not_found(mut stream: TcpStream) {
    let response = "HTTP/1.1 404 NOT FOUND\r\n\r\n";
    stream.write(response.as_bytes()).unwrap();
    stream.flush().unwrap();
}

fn handle_client(mut stream: TcpStream) {
    let mut buffer = [0; 1024];
    stream.read(&mut buffer).unwrap();
    let request = String::from_utf8_lossy(&buffer[..]);

    let path = request.lines().next().unwrap().split_whitespace().nth(1).unwrap();

    match path {
        "/" => handle_root(stream),
        _ => handle_not_found(stream),
    }
}

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

    for stream in listener.incoming() {
        match stream {
            Ok(stream) => {
                std::thread::spawn(|| {
                    handle_client(stream)
                });
            }
            Err(e) => { println!("{:?}", e) }
        }
    }

    drop(listener);
}
1213 chars
46 lines

This code parses the incoming HTTP request and extracts the requested path. If the path is "/", the handle_root() function is called, which returns a JSON response containing a "message" field. For any other path, the handle_not_found() function is called, which returns a 404 response.

gistlibby LogSnag