67 lines
1.5 KiB
Rust
67 lines
1.5 KiB
Rust
#[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])
|
|
}
|