Skip to content

Instantly share code, notes, and snippets.

@ezesundayeze
Created September 1, 2023 07:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ezesundayeze/ba791d7323ab21153c2e814a0817904f to your computer and use it in GitHub Desktop.
Save ezesundayeze/ba791d7323ab21153c2e814a0817904f to your computer and use it in GitHub Desktop.
A simple Rust based server with no framework
use std::net::{TcpListener, TcpStream};
use std::io::{Read, Write};
/// Handles an incoming client TCP stream.
///
/// # Arguments
///
/// * `stream` - The TCP stream for the connected client.
///
/// # Panics
///
/// Panics if there is an error reading from or writing to the stream.
fn handle_client(mut stream: TcpStream) {
let mut buffer = [0; 1024];
let bytes_read = stream.read(&mut buffer).unwrap();
let request: std::borrow::Cow<'_, str> = String::from_utf8_lossy(&buffer[..bytes_read]);
if request.starts_with("GET /") {
// Handling a GET request
let response = "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\r\n{\"message\": \"Hello from Rust Web Server!\"}";
stream.write(response.as_bytes()).unwrap();
} else if request.starts_with("POST /") {
// Handling a POST request
if let Some(body_start) = request.find("\r\n\r\n") {
let body = &request[(body_start + 4)..];
// handle POST request body
// Process the received data and generate a response
let response = format!(
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\r\n{}", body
);
stream.write(response.as_bytes()).unwrap();
}
}
stream.flush().unwrap();
}
/// Starts a TCP server listening on localhost port 8080.
///
/// For each incoming stream, spawns a new thread to handle the client
/// connection.
fn main() {
let listener = TcpListener::bind("127.0.0.1:8080").expect("Failed to bind to address");
for stream in listener.incoming() {
match stream {
Ok(stream) => {
std::thread::spawn(|| {
handle_client(stream);
});
}
Err(e) => {
eprintln!("Error: {}", e);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment