Created
July 21, 2022 16:57
-
-
Save peacock0803sz/767cc1d3e6fbf8b605ca072f30e4720e to your computer and use it in GitHub Desktop.
Tiny HTTP Server in Rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::io::prelude::*; | |
use std::net::{TcpListener, TcpStream}; | |
use std::thread; | |
const RESPONSE: &[u8] = "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\n\r\n\ | |
<!DOCTYPE html><html><head><title>Welcome to tiny-http!</title></head>\ | |
<body><h1>Welcome to tiny-http!</h1></body></html>" | |
.as_bytes(); | |
fn handle_client(mut stream: TcpStream) { | |
let mut buffer = [0u8; 4096]; | |
match stream.read(&mut buffer) { | |
Ok(_) => { | |
let s = String::from_utf8_lossy(&buffer); | |
println!("{}", s); | |
} | |
Err(e) => println!("Could not to read stream: {}", e), | |
} | |
match stream.write(RESPONSE) { | |
Ok(_) => println!("Response sent"), | |
Err(e) => println!("Failed to send response... {}", e), | |
} | |
} | |
fn main() { | |
let listener = TcpListener::bind("127.0.0.1:8080").unwrap(); | |
for stream in listener.incoming() { | |
match stream { | |
Ok(stream) => { | |
thread::spawn(|| { | |
handle_client(stream); | |
}); | |
} | |
Err(e) => panic!("Uncaught HTTP response... {}", e), | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Demo