http_str

Crates.iohttp_str
lib.rshttp_str
version0.1.3
sourcesrc
created_at2019-12-15 01:13:35.505892
updated_at2019-12-15 20:08:36.785416
descriptionThis is a Rust libray that provides some types for parsing http request and create responses.
homepage
repositoryhttps://github.com/NonNullableName/http_str
max_upload_size
id189465
size24,950
Dang (NonNullableName)

documentation

https://docs.rs/http_str/0.1.3/http_str/

README

http_str

This is a Rust libray that provides some types for parsing http request and create responses.

Usage

use std::net::{TcpListener, TcpStream};
use std::io::prelude::*;
use std::io;
use http_str::Request;
use std::fs::File;
use std::collections::BTreeMap;
use std::str::from_utf8;

fn main() -> io::Result<()> {
    let tcp_listener = TcpListener::bind("127.0.0.1:7878")?;
    
    for stream in tcp_listener.incoming() {
        let stream = stream?;
        handle_connection(stream)?;
    }
}

fn handle_connection(stream: TcpStream) -> io::Result<()> {
    let mut buffer = [0; 512];
    stream.read_exact(&mut buffer)?;
    
    let request = Request::new(&buffer[..]);
    let mut body = [0; 512];
    let file = File::open(request.uri)?;
    file.read_exact(&mut body)?;
    let mut string = String::new();
    
    let response = Response::new(request.version,
                    200, 
                    BTreeMap::new(), // headers
                    from_utf8(&body[..]).unwrap(), 
                    &mut string); 
    
    stream.write_all(response.as_bytes())?;
    stream.flush()?;
    
    Ok(())
}
Commit count: 0

cargo fmt