Skip to content

DanielGrotan/rust-http

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

12 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Rust HTTP library

A lightweight asynchronous HTTP server library in Rust. Provides:

  • TCP-based HTTP parsing
  • Async request handling with tokio
  • Builder-style server and router API
  • Easy header and body access for handlers

Features

  • Minimal, no heavy dependencies besides tokio
  • Async-first design - handlers are async fns
  • Incremental HTTP parsing for efficiency
  • Builder pattern for configurating routes
  • Easily integrated into other projects as a library

Installation

From github

[dependencies]
rust_http = { git = "https://github.com/danielgrotan/rust-http.git" }
tokio = { version = "1", features = ["full"] }

Usage

Basic example

use rust_http::{Request, Response, Server};

#[tokio::main]
async fn main() {
    let mut server = Server::bind("127.0.0.1:3000")
        .get("/hello", handle_hello)
        .build();

    server.run().await;
}

async fn handle_hello(req: Request) -> Response {
    Response::ok(
        req.headers
            .get("user-agent")
            .map(|user_agent| format!("Hello {}!", user_agent))
            .unwrap_or_else(|| "Who are you? Give me your user agent ;(".to_string()),
    )
}

API Highlights

Server

  • Server::bind(addr) -> returns a ServerBuilder
  • .get(path, handler) -> registers a GET route with an async handler
  • .post(path, handler) -> registers a POST route with an async handler
  • .build() -> builds the server
  • .run().await -> starts listening and serving requests

Request

  • request_line: HTTP method, path, and version
  • headers: header map with helpers get / get_or
  • body: optional body as Vec<u8>

Response

  • Response::ok(body) -> create a 200 OK response
  • .with_header(key, value) -> add HTTP headers
  • .as_bytes() -> convert the response to raw bytes for writing to TCP

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages