first commit
This commit is contained in:
commit
2b495644d6
2 changed files with 77 additions and 0 deletions
10
Cargo.toml
Normal file
10
Cargo.toml
Normal file
|
@ -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"
|
67
src/main.rs
Normal file
67
src/main.rs
Normal file
|
@ -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<Mutex<Db>>) -> Json<i32> {
|
||||
let db = db.lock().unwrap();
|
||||
Json(db.count)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct KeyInput {
|
||||
key: String,
|
||||
}
|
||||
|
||||
#[post("/increment", data = "<input>")]
|
||||
fn increment_count(input: Json<KeyInput>, db: &State<Mutex<Db>>) -> &'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])
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue