Skip to content

Instantly share code, notes, and snippets.

@peacock0803sz
Created July 21, 2022 16:57
Show Gist options
  • Save peacock0803sz/767cc1d3e6fbf8b605ca072f30e4720e to your computer and use it in GitHub Desktop.
Save peacock0803sz/767cc1d3e6fbf8b605ca072f30e4720e to your computer and use it in GitHub Desktop.
Tiny HTTP Server in Rust
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),
}
}
}
@peacock0803sz
Copy link
Author

Demo

CleanShot 2022-07-22 at 02 00 20

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment