|
| 1 | +use std::io::{BufRead, BufReader, Write}; |
| 2 | +use std::net::{TcpListener, TcpStream}; |
| 3 | + |
| 4 | +fn get_operation(stream: &mut TcpStream) -> std::io::Result<()> { |
| 5 | + let body = "HTTP server sample"; |
| 6 | + writeln!(stream, "HTTP/1.1 200 OK")?; |
| 7 | + writeln!(stream, "Content-Type: text/plain; charset=UTF-8")?; |
| 8 | + writeln!(stream, "Content-Length: {}", body.len())?; |
| 9 | + writeln!(stream)?; |
| 10 | + |
| 11 | + writeln!(stream, "{}", body)?; |
| 12 | + Ok(()) |
| 13 | +} |
| 14 | + |
| 15 | +fn handle_client(stream: TcpStream) -> std::io::Result<()> { |
| 16 | + let mut reader = BufReader::new(stream); |
| 17 | + |
| 18 | + let mut first_line = String::new(); |
| 19 | + reader.read_line(&mut first_line)?; |
| 20 | + |
| 21 | + let mut params = first_line.split_whitespace(); |
| 22 | + let method = params.next(); |
| 23 | + let path = params.next(); |
| 24 | + match (method, path) { |
| 25 | + (Some("GET"), Some(_)) => { |
| 26 | + get_operation(reader.get_mut())?; |
| 27 | + } |
| 28 | + _ => panic!("failed to parse"), |
| 29 | + } |
| 30 | + Ok(()) |
| 31 | +} |
| 32 | + |
| 33 | +fn main() -> std::io::Result<()> { |
| 34 | + let listener = TcpListener::bind("127.0.0.1:8080")?; |
| 35 | + |
| 36 | + for stream in listener.incoming() { |
| 37 | + handle_client(stream?)?; |
| 38 | + } |
| 39 | + Ok(()) |
| 40 | +} |
0 commit comments