From 640d23a6177f7a34c7e6433f528149957fce4e94 Mon Sep 17 00:00:00 2001 From: holly sparkles Date: Mon, 2 Oct 2023 13:02:34 +0200 Subject: [PATCH] feat: add api endpoints using tide --- Cargo.toml | 2 ++ src/main.rs | 75 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 75 insertions(+), 2 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 36364f3..c281cbb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,3 +6,5 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +async-std = { version = "1.12.0", features = ["attributes"] } +tide = "0.16.0" diff --git a/src/main.rs b/src/main.rs index e7a11a9..358ed37 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,74 @@ -fn main() { - println!("Hello, world!"); +use tide::{http::mime, log, Response, Result, Server, StatusCode}; + +const BASE_URL: &str = "/api"; + +#[async_std::main] +async fn main() -> Result<()> { + let mut app = tide::new(); + log::start(); + + create_routes(&mut app); + + app.listen("127.0.0.1:8080").await?; + Ok(()) +} + +fn create_routes(server: &mut Server<()>) { + let mut base_route = server.at(BASE_URL); + base_route.get(get_welcome_message); + + base_route.at("/:license").get(get_requested_license); + base_route.at("/list").get(get_license_list); + base_route.at("/list/full").get(get_detailed_license_list); + + // nyaaaaa whyyyy https://github.com/http-rs/tide/issues/205 + base_route.at("").get(get_welcome_message); + base_route.at("/list/").get(get_license_list); + base_route.at("/list/full/").get(get_detailed_license_list); +} + +fn build_response(status: StatusCode, data: String) -> Response { + // this is a plain text only service + let response = Response::builder(status) + .body(format!("{}\n", data)) + .content_type(mime::PLAIN) + .build(); + + response +} + +async fn get_welcome_message(req: tide::Request<()>) -> tide::Result { + log::info!("{:?}", req); + + Ok(build_response( + StatusCode::Ok, + format!("{}", "Welcome message goes here").to_string(), + )) +} + +async fn get_license_list(req: tide::Request<()>) -> tide::Result { + log::info!("{:?}", req); + + Ok(build_response( + StatusCode::Ok, + format!("{}", "License list goes here").to_string(), + )) +} + +async fn get_detailed_license_list(req: tide::Request<()>) -> tide::Result { + log::info!("{:?}", req); + + Ok(build_response( + StatusCode::Ok, + format!("{}", "License list with full names goes here").to_string(), + )) +} + +async fn get_requested_license(req: tide::Request<()>) -> tide::Result { + log::info!("{:?}", req); + + Ok(build_response( + StatusCode::Ok, + format!("{}", "Content of requested license goes here").to_string(), + )) } -- libgit2 1.7.2