Skip to content

Instantly share code, notes, and snippets.

@phanmn
Created April 12, 2024 08:20
Show Gist options
  • Save phanmn/98d6c96e11e884e2d36b5ded9b10ff85 to your computer and use it in GitHub Desktop.
Save phanmn/98d6c96e11e884e2d36b5ded9b10ff85 to your computer and use it in GitHub Desktop.
Rust Simple Http Server
use std::io::{Read, Write};
use std::net::TcpListener;
fn main() -> std::io::Result<()> {
let listener = TcpListener::bind("127.0.0.1:9000")?;
println!("Listening on port 9000");
for conn in listener.incoming() {
let mut conn = conn?;
let mut buffer = [0; 4048];
let read_result = conn.read(&mut buffer);
if let Err(io_err) = &read_result {
log::error!("Error reading incoming connection: {}", io_err.to_string());
};
let read_byte = read_result.unwrap();
let mut headers = [httparse::EMPTY_HEADER; 16];
let mut request = httparse::Request::new(&mut headers);
request.parse(&buffer).ok().unwrap();
let mut content_length = 0;
for header in &headers {
if header.name == "Content-Length" {
content_length = String::from_utf8_lossy(header.value)
.to_string()
.parse()
.unwrap();
}
}
let mut request_body = "".to_string();
if content_length > 0 {
let request_string = String::from_utf8_lossy(&buffer[..read_byte]);
let parts: Vec<&str> = request_string.splitn(2, "\r\n\r\n").collect();
let mut content = parts.get(1).unwrap_or(&"").to_string();
let not_read_bytes = content_length - content.len();
if not_read_bytes > 0 {
let mut body_buffer = vec![0; not_read_bytes];
conn.read_exact(&mut body_buffer).unwrap();
let missing = String::from_utf8_lossy(&body_buffer).to_string();
content.push_str(&missing);
}
request_body = content;
}
// Process request (replace with your logic)
let response = format!("Hello, world! You sent: {}", request_body);
// Send HTTP response
let response = format!(
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n{}",
response.len(),
response
);
conn.write_all(response.as_bytes())?;
println!("Response sent");
}
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment