diff --git a/README.md b/README.md index 76f29b6..0b286dc 100644 --- a/README.md +++ b/README.md @@ -40,5 +40,4 @@ base URL to prepend to the `POST` responses will be configured using a config fi After implementing a very basic API with `GET` and `POST` requests, I'm planning to add the following features. - [x] HTTP basic authentication for posting/deleting pastes. - [x] Syntax highlighting with [syntect](https://github.com/trishume/syntect). -- [ ] `DELETE` method to delete pastes. - [ ] Configuration via a config file. diff --git a/src/lib.rs b/src/lib.rs index 20bd9a2..f2e0c82 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -30,6 +30,11 @@ pub fn run(config: Config) -> Result<(), Box> { .service( web::resource("/") .route(web::post().to_async(new_paste)) + .wrap(basic_auth.clone()), + ) + .service( + web::resource("/{paste_id}") + .route(web::delete().to_async(delete_paste)) .wrap(basic_auth), ) .service(send_paste) @@ -107,6 +112,20 @@ fn new_paste( }) } +fn delete_paste( + config: web::Data, + paste_id: web::Path, +) -> impl Future { + web::block(move || { + let file_path = format!("{}/{}", config.paste_dir, paste_id); + fs::remove_file(file_path) + }) + .then(|res| match res { + Ok(_) => Ok(HttpResponse::Ok().body("")), + Err(_) => Ok(HttpResponse::NotFound().into()), + }) +} + #[get("/{paste_id}")] fn send_paste( config: web::Data, @@ -285,6 +304,35 @@ mod tests { assert_eq!(paste_content, file_content); } + #[test] + fn delete_paste_file() { + let test_dir = TempDir::new().unwrap(); + let config = make_test_config(test_dir.path().to_str().unwrap()); + + let data = web::Data::new(config.clone()); + let mut app = test::init_service( + App::new() + .register_data(data) + .route("/{paste_id}", web::delete().to_async(delete_paste)), + ); + + let paste_id = "/testpaste"; + let paste_path = config.paste_dir + paste_id; + { + let paste_content = b"nonsense"; + let mut file = File::create(&paste_path).unwrap(); + file.write_all(paste_content).unwrap(); + } + + let req = test::TestRequest::delete().uri(paste_id).to_request(); + let resp = test::call_service(&mut app, req); + assert_eq!(resp.status(), http::StatusCode::OK); + assert!( + File::open(paste_path).is_err(), + "Deleted paste file should not exist" + ); + } + #[test] fn auth_valid_creds() { let config = make_test_config("unused path");