commit 2b495644d674a4c222cddc6873e8e0f78ea04ac2 Author: Andrea Date: Wed Jul 2 22:07:47 2025 +0200 first commit diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..f6504e3 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "count-api" +version = "0.1.0" +edition = "2024" + +[dependencies] +rocket = { version = "0.5.1", features = ["json"] } +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" +rand = "0.9.1" \ No newline at end of file diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..fdd0c46 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,67 @@ +#[macro_use] extern crate rocket; + +use rocket::serde::{Serialize, Deserialize}; +use std::fs; +use std::sync::Mutex; +use rocket::State; +use rocket::serde::json::Json; +use rand::{Rng, distr::Alphanumeric}; + +const DB_PATH: &str = "db.json"; + +#[derive(Serialize, Deserialize, Debug, Clone)] +struct Db { + count: i32, + key: String, +} + +fn read_db() -> Db { + let data = fs::read_to_string(DB_PATH).unwrap_or_else(|_| "{\"count\":0,\"key\":\"\"}".to_string()); + let mut db: Db = serde_json::from_str(&data).unwrap_or(Db { count: 0, key: String::new() }); + if db.key.is_empty() { + db.key = rand::rng().sample_iter(&Alphanumeric).take(16).map(char::from).collect(); + write_db(&db); + } + db +} + +fn write_db(db: &Db) { + let data = serde_json::to_string_pretty(db).unwrap(); + fs::write(DB_PATH, data).unwrap(); +} + +#[get("/")] +fn index() -> &'static str { + "What u looking for?" +} + +#[get("/count")] +fn get_count(db: &State>) -> Json { + let db = db.lock().unwrap(); + Json(db.count) +} + +#[derive(Deserialize)] +struct KeyInput { + key: String, +} + +#[post("/increment", data = "")] +fn increment_count(input: Json, db: &State>) -> &'static str { + let mut db = db.lock().unwrap(); + if input.key == db.key { + db.count += 1; + write_db(&db); + "Count incremented" + } else { + "Invalid key" + } +} + +#[launch] +fn rocket() -> _ { + let db = read_db(); + rocket::build() + .manage(Mutex::new(db)) + .mount("/", routes![index, get_count, increment_count]) +}