#http #server

tinyhttp

A HTTP library with SSL and GZIP support

20 releases

0.4.0-rc5 Dec 7, 2023
0.4.0-rc3 Oct 14, 2023
0.4.0-rc1 Jul 10, 2023
0.3.2 Mar 29, 2023
0.2.7 Jul 1, 2022

#314 in HTTP server

GPL-2.0-or-later

14KB
190 lines

tinyhttp

tinyhttp is a fast, multi-threaded http server with procedural macros to make life easier.

You can also combine examples, e.g with a mount point and custom routes

Example 1: Using a mount point

use std::net::TcpListener;
use tinyhttp::internal::config::*;
fn main() {
  let socket = TcpListener::bind(":::9001").unwrap();
  let mount_point = ".";
  let config = Config::new().mount_point(mount_point);
  let http = HttpListener::new(socket, config);

  http.start();
}

Example 2: Using proc macros


/// Functions marked with the get macro must return with a type of Into<Vec<u8>>
use std::net::TcpListener;
use tinyhttp::prelude::*;
#[get("/")]
fn get() -> &'static str {
 "Hello, World!"
}

#[post("/")]
fn post() -> &'static str {
  "Hello, there!"
}

fn main() {
  let socket = TcpListener::bind(":::80").unwrap();
  let routes = Routes::new(vec![get(), post()]);
  let config = Config::new().routes(routes);
  let http = HttpListener::new(socket, config);

  http.start();
}

All route functions must be included in the Routes::new(vec![])

Diving into the route functions

As of now, route functions can return anything that is Into<Vec<u8>> or a Response

use tinyhttp::prelude::*;

// Example 1: returns anything Into<Vec<u8>>
#[get("/")]
fn ex1_get() -> &'static str {
    "Hello World!"
}

// Example 2: same as example 1, but takes a Request as an argument
#[get("/ex2")]
fn ex2_get(req: Request) -> String {
    let headers = req.get_headers();
    let accept_header = headers.get("accept").unwrap();
    format!("accept header: {}", accept_header)
}

// Example 3: takes a Request as an argument and returns a Response for more control
#[get("/ex3")]
fn ex3_get(req: Request) -> Response {
    Response::new()
        .status_line("HTTP/1.1 200 OK\r\n")
        .mime("text/plain")
        .body(b"Hello from response!\r\n".to_vec())
}

Dependencies

~2–14MB
~146K SLoC