Skip to content

ohkami-rs/whttp

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

48 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

whttp

A new, opinionated implementation of HTTP types for Rust

License CI status crates.io

What's the advantage over http crate?

fast and efficient

  • swiss table (by hashbrown) and pre-calculated fxhash for Headers
  • pre-matches standard headers before hashing during parsing
  • Request construction with zero or least copy from parsing buffer and minimum allocation
  • size of Request is 128, and size of Response is 64
  • micro benchmarks

batteries included

  • consistent and clear API
  • builtin support for Cookie, Set-Cookie, IMF-fixdate header values, and JSON response bodies
  • Server-Sent Events on sse feature
  • WebSocket on ws & rt_* feature
  • HTTP/1.1 parsing & writing on http1 & rt_* feature
  • supported runtimes ( on rt_* ) : tokio, async-std, smol, glommio
[dependencies]
whttp = { version = "0.1", features = ["http1", "rt_tokio"] }
tokio = { version = "1", features = ["full"] }
use whttp::{Request, Response, http1};
use whttp::header::{ContentType, Date};
use whttp::util::IMFfixdate;

#[tokio::main]
async fn main() -> std::io::Result<()> {
    let listener = tokio::net::TcpListener::bind("localhost:3000").await?;

    while let Ok((mut conn, addr)) = listener.accept().await {
        let mut req = http1::init();
        let mut req = std::pin::Pin::new(&mut req);

        while let Ok(Some(())) = http1::load(
            req.as_mut(), &mut conn
        ).await {
            let res = handle(&req).await;
            http1::send(res, &mut conn).await?;
        }
    }

    Ok(())
}

async fn handle(req: &Request) -> Response {
    if !(req.header(ContentType)
            .is_some_and(|ct| ct.starts_with("text/plain"))
    ) {
        return Response::BadRequest()
            .with(Date, IMFfixdate::now())
            .with_text("expected text payload")
    }

    let name = std::str::from_utf8(req.body().unwrap()).unwrap();

    Response::OK()
        .with(Date, IMFfixdate::now())
        .with_text(format!("Hello, {name}!"))
}

License

whttp is licensed under MIT LICENSE ( LICENSE or https://opensource.org/licenses/MIT ).

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages