From 9401dcc598bc052957f81fab164a35905fd4ef4f Mon Sep 17 00:00:00 2001 From: Shautvast Date: Fri, 6 Feb 2026 16:06:50 +0100 Subject: [PATCH] #10 a conditional response --- call.http | 4 +++- src/main.rs | 25 +++++++++++++++---------- 2 files changed, 18 insertions(+), 11 deletions(-) diff --git a/call.http b/call.http index c301ab6..6143036 100644 --- a/call.http +++ b/call.http @@ -1 +1,3 @@ -GET http://127.0.0.1:7878/ \ No newline at end of file +GET http://127.0.0.1:7878/ +### +POST http://127.0.0.1:7878/ \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index ffc1587..4c0a7f4 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,14 +1,14 @@ +use log::info; use std::io::{Read, Write}; use std::net::{TcpListener, TcpStream}; -use env_logger::Logger; -use log::info; + +static GET: &'static [u8] = b"GET / HTTP/1.1\r\n"; fn main() -> std::io::Result<()> { env_logger::init(); let listener = TcpListener::bind("127.0.0.1:7878")?; for stream in listener.incoming() { - let stream = stream?; - handle_connection(stream)?; + handle_connection(stream?)?; } Ok(()) } @@ -18,12 +18,17 @@ fn handle_connection(mut stream: TcpStream) -> std::io::Result<()> { stream.read(&mut buffer)?; info!("Request: {}", String::from_utf8_lossy(&buffer[..])); - let contents = include_str!("hello.html"); - let response = format!( - "HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n{}", - contents.len(), - contents - ); + let response = if buffer.starts_with(GET) { + let contents = include_str!("hello.html"); + format!( + "HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n{}", + contents.len(), + contents + ) + } else { + "HTTP/1.1 405 Method not allowed\r\n\r\n".to_string() + }; + stream.write(response.as_bytes())?; stream.flush()?; Ok(())