create a http server on a specific port in rust

To create an HTTP server on a specific port in Rust, we can make use of the standard library's TcpListener and TcpStream to listen to incoming requests and send responses. Here's some sample code to create a basic server on port 8000:

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

fn main() -> std::io::Result<()> {
    let listener = TcpListener::bind("127.0.0.1:8000")?;

    for stream in listener.incoming() {
        let mut stream = stream.expect("Failed to get stream");
        let mut buffer = [0; 1024];

        stream.read(&mut buffer).expect("Failed to read from stream");

        let response = "HTTP/1.1 200 OK\r\n\r\nHello, World!";
        stream.write(response.as_bytes()).expect("Failed to write to stream");
        stream.flush().expect("Failed to flush stream");
    }

    Ok(())
}
578 chars
20 lines

In this code, we first create a TcpListener that listens on 127.0.0.1:8000, which means it will only accept connections from the local machine on port 8000. Then, we loop through incoming connections with listener.incoming() and read from the stream with stream.read(). We then generate an HTTP response and write it back to the client with stream.write() and stream.flush(). The server will continue to run until it is interrupted, such as with a Ctrl+C command.

Of course, this is just a basic example and a real-world HTTP server would require additional functionality, such as routing requests to the appropriate handlers, parsing headers and request bodies, and handling errors. However, this code should provide a starting point for creating an HTTP server in Rust.

gistlibby LogSnag