Creating http server

I'm learning how to code bidirectional connection between server and client. So far my server can respond with any form of data I've tested it with, but there's something keeping me restless. Clients doing post|put|patch requests with file data as body arrive with empty bodies except 'application/x-www-form-urlencoded' data. How can I solve this? Here is my server code(just for learning purpose):

use std::{
  net::TcpListener,
  io::prelude::*,
  thread::{
    self,
    Scope
  }
};

static RESPONSE: [&'static str; 10] = [
  "HTTP/1.1 200 Ok",
  "Content-Length: 25",
  "Content-Type: text/plain",
  "Content-Encoding: identity",
  "Access-Control-Allow-Methods: *",
  "Access-Control-Allow-Origin: *",
  "Access-Control-Allow-Headers: *",
  "Accept-Encoding: *",
  "Accept: */*\r\n",
  "Grateful checking on me.\n"
];

fn main() {
  let listener = TcpListener::bind("127.0.0.1:8000").unwrap();
  println!("Listening at localhost:8000");
  thread::scope(|here| handle_connections(here, &listener));
}

fn handle_connections<'scope, 'env>(scope: &'scope Scope<'scope, 'env>, listener: &'env TcpListener) {
  let actor = thread::Builder::new().spawn_scoped(scope, move || loop {
    match listener.accept() {
      Ok((mut client, addr)) => {
        println!("Connection from: {}.", addr);
        let mut buff = [0; 1024];
        client.read(&mut buff).unwrap();
        match client.write_all(RESPONSE.join("\r\n").as_bytes()) {
          Ok(_) => println!("Send successful."),
          Err(err) => eprintln!("Send failed: {}", err),
        }
        println!("{}\n", String::from_utf8(buff.to_vec()).unwrap()); // for debugging
      }
      Err(_) => eprintln!("Connection failed or disrupted!"),
    }
  });
  
  if let Err(err) = actor {
    eprintln!("Recovering from: {}", err);
    handle_connections(scope, listener);
  }
}

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.