From 39795fa675bcc97febbac7da0f7f0c7a0332549e Mon Sep 17 00:00:00 2001 From: jabuxas Date: Tue, 11 Feb 2025 08:32:22 -0300 Subject: [PATCH] feat: add basic post and get logic --- .gitignore | 1 + src/main.rs | 66 ++++++++++++++++++++++++++++++++++++++++++++++------- 2 files changed, 59 insertions(+), 8 deletions(-) diff --git a/.gitignore b/.gitignore index ea8c4bf..955b37c 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ /target +/store diff --git a/src/main.rs b/src/main.rs index fe329d6..025cca8 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,19 +1,69 @@ #[macro_use] extern crate rocket; -#[get("/")] -fn index() -> &'static str { - "Hello, world!" +use rocket::form::Form; +use rocket::fs::TempFile; +use rocket::tokio::io::AsyncWriteExt; +use rocket::tokio::fs::File; +use rocket::tokio::io::AsyncReadExt; +use rocket::fs::NamedFile; +use rocket::get; +use std::path::{Path, PathBuf}; + +#[derive(FromForm)] +struct Upload<'r> { + save: bool, + file: TempFile<'r>, } #[get("/")] -fn world() -> &'static str { - "world!" +fn index() -> &'static str { + "

hey, index is working

" +} + +#[get("/")] +async fn file(file: PathBuf) -> Option { + let path = Path::new("./store").join(file); + + NamedFile::open(path).await.ok() +} + +#[post("/", data = "")] +async fn upload(upload: Form>) -> String { + std::fs::create_dir_all("./store").expect("Failed to create directory"); + + let upload = upload.into_inner(); + + let filename: String = upload + .file + .name() + .and_then(|n| std::path::Path::new(n).file_name()) + .and_then(|n| n.to_str()) + .map(|s| s.to_owned()) + .unwrap_or_else( || "unknown.bin".to_owned()); + + let path = std::path::Path::new("./store").join(&filename); + + let mut tmp_file = upload.file.open().await.expect("Failed to open temp file"); + let mut dest_file = File::create(&path) + .await + .expect("Failed to create destination file"); + + let mut buffer = Vec::new(); + tmp_file + .read_to_end(&mut buffer) + .await + .expect("Failed to read temporary file"); + dest_file + .write_all(&buffer) + .await + .expect("Failed to write destination file"); + + + format!("http://localhost:8000/{}\n", filename) } #[launch] fn rocket() -> _ { - rocket::build() - .mount("/", routes![index]) - .mount("/world", routes![world]) + rocket::build().mount("/", routes![index, upload, file]) }