#10 a conditional response
This commit is contained in:
parent
fabdffbafa
commit
9401dcc598
2 changed files with 18 additions and 11 deletions
|
|
@ -1 +1,3 @@
|
||||||
GET http://127.0.0.1:7878/
|
GET http://127.0.0.1:7878/
|
||||||
|
###
|
||||||
|
POST http://127.0.0.1:7878/
|
||||||
25
src/main.rs
25
src/main.rs
|
|
@ -1,14 +1,14 @@
|
||||||
|
use log::info;
|
||||||
use std::io::{Read, Write};
|
use std::io::{Read, Write};
|
||||||
use std::net::{TcpListener, TcpStream};
|
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<()> {
|
fn main() -> std::io::Result<()> {
|
||||||
env_logger::init();
|
env_logger::init();
|
||||||
let listener = TcpListener::bind("127.0.0.1:7878")?;
|
let listener = TcpListener::bind("127.0.0.1:7878")?;
|
||||||
for stream in listener.incoming() {
|
for stream in listener.incoming() {
|
||||||
let stream = stream?;
|
handle_connection(stream?)?;
|
||||||
handle_connection(stream)?;
|
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
@ -18,12 +18,17 @@ fn handle_connection(mut stream: TcpStream) -> std::io::Result<()> {
|
||||||
stream.read(&mut buffer)?;
|
stream.read(&mut buffer)?;
|
||||||
info!("Request: {}", String::from_utf8_lossy(&buffer[..]));
|
info!("Request: {}", String::from_utf8_lossy(&buffer[..]));
|
||||||
|
|
||||||
let contents = include_str!("hello.html");
|
let response = if buffer.starts_with(GET) {
|
||||||
let response = format!(
|
let contents = include_str!("hello.html");
|
||||||
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n{}",
|
format!(
|
||||||
contents.len(),
|
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n{}",
|
||||||
contents
|
contents.len(),
|
||||||
);
|
contents
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
"HTTP/1.1 405 Method not allowed\r\n\r\n".to_string()
|
||||||
|
};
|
||||||
|
|
||||||
stream.write(response.as_bytes())?;
|
stream.write(response.as_bytes())?;
|
||||||
stream.flush()?;
|
stream.flush()?;
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue