DEV Community

Stacy Roll
Stacy Roll

Posted on

1 2 1 1 1

Dynamic HTTP API for web & OS dev 🧢

Today we'll be writing a working web API using an extremely simple HTTP library controlable from the console of your computer. Let gonna se the implementation

First, crate a new folder and add k_board & snowboard.

cargo new http-api && cd http-api && cargo add k_board && cargo add snowboard

use k_board::{Keyboard, Keys};
use snowboard::{response, Server};

fn main() {
    for key in Keyboard::new() {
        match key {
            Keys::Enter => router("localhost:3000"),
            Keys::Letter('q') => break,
            _ => {}
        }
    }
}

fn router(localhost: &str) {
    println!("Running in localhost:3000 - `curl localhost:3000`");
    Server::new(localhost).run(|req| {
        println!("Request: {:?}", req);
        response!(ok, "You are in localhost 3000!\n")
    });
}
Enter fullscreen mode Exit fullscreen mode

If you press enter you active the server listening all call, then when you make a curl localhost:300 you will receive the answer of the server.

mateo@debian:~/http-api$ curl localhost:3000
You are in localhost 3000!
Enter fullscreen mode Exit fullscreen mode

That a simple example in which it just take the enter key as an activator of the server, if your looking for an specific handling of the keys for server activation , you can look at Keys struct of k_board.

pub enum Keys {
    Up,
    Down,
    Left,
    Right,
    Enter,
    Space,
    Delete,
    Escape,
    Plus,
    Minus,
    Equal,
    Power,                 ^
    Slash,                 /
    Backslash,             \
    Asterisk,              *
    Point,
    Comma,
    Hashtag,
    Pipe,                  |
    Percent,               %
    Ampersand,
    Currency,              $
    TwoPoints,             :
    Semicolon,             ;
    OpenSquareBracket,     [
    CloseSquareBracket,    ]
    OpenCurlyBrace,        {
    CloseCurlyBrace,       }
    OpenQuestionMark,      ¿
    CloseQuestionMark,     ?
    OpenParenthesis,       (
    CloseParenthesis,      )
    LessThan,              <
    GreaterThan,           >
    Apostrophe,            ' 
    At,                    @
    Home,
    End,
    Tab,
    Backtab,
    Insert,
    Letter(char),
    Number(u8),
    F(u8),
    Ctrl(char),
    Alt(char),
    Null,
}
Enter fullscreen mode Exit fullscreen mode

API Trace View

Struggling with slow API calls?

Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More