use axum::{ routing::{get, post}, http::StatusCode, response::Html, extract::{State, Query}, Json, Router, }; use serde::{Deserialize, Serialize}; use serde_json::json; use chrono::Local; use std::sync::Arc; use std::fs::{create_dir_all, File}; use std::io::{self, Write}; use std::path::Path; #[tokio::main] async fn main() { // initialize tracing tracing_subscriber::fmt::init(); // build our application with a route let app = Router::new() // `GET /` goes to `root` .route("/", get(root)) // `POST /users` goes to `create_user` .route("/submit", post(submit_text)); // run our app with hyper, listening globally on port 3000 let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); axum::serve(listener, app).await.unwrap(); } fn create_directory_hierarchy(payload: String, tags: Vec<&str>) -> io::Result<()> { let now = Local::now(); let base_dir = "/home/builder/chrons"; let path = now.format("%Y/%m/%d/%H-%M.txt").to_string(); let full_path = Path::new(base_dir).join(path); let dir_path = full_path.parent().unwrap(); create_dir_all(dir_path)?; let mut file = File::create(&full_path)?; writeln!(file, "* Entry {}", now.format("%d-%m-%Y %H:%M").to_string())?; for tag in tags.iter() { writeln!(file, "tag: {}", tag.trim())?; } writeln!(file, "\n{payload}")?; Ok(()) } fn get_current_datetime() -> String { let now = Local::now(); now.format("%d-%m-%y %H:%M").to_string() } async fn root() -> Html { let reg = handlebars::Handlebars::new(); let html = reg.render_template( include_str!("../main.handlebars"), &json!({}), ).unwrap(); let cfg = minify_html::Cfg { minify_css: true, minify_js: true, ..Default::default() }; let html = minify_html::minify(html.as_bytes(), &cfg); let html = String::from_utf8_lossy(&html).to_string(); Html(html) } async fn submit_text( // this argument tells axum to parse the request body // as JSON into a `CreateUser` type Json(payload): Json, ) -> StatusCode { // insert your application logic here let tags: Vec<&str> = payload.tags.split(",").collect(); println!("{}", payload.text); let _ = create_directory_hierarchy(payload.text, tags); // this will be converted into a JSON response // with a status code of `201 Created` StatusCode::CREATED } #[derive(Deserialize)] struct Entry { tags: String, text: String, }