Rocket/examples/pastebin/src/main.rs

55 lines
1.2 KiB
Rust
Raw Normal View History

#[macro_use] extern crate rocket;
2016-12-10 03:56:49 +00:00
mod paste_id;
2017-04-14 21:39:17 +00:00
#[cfg(test)] mod tests;
2016-12-10 03:56:49 +00:00
use std::io;
use rocket::Data;
use rocket::response::{content::Plain, Debug};
use rocket::tokio::fs::File;
2016-12-10 03:56:49 +00:00
2019-06-13 02:41:29 +00:00
use crate::paste_id::PasteID;
2016-12-10 03:56:49 +00:00
2018-07-28 16:58:10 +00:00
const HOST: &str = "http://localhost:8000";
2016-12-10 03:56:49 +00:00
const ID_LENGTH: usize = 3;
#[post("/", data = "<paste>")]
2019-08-27 23:40:23 +00:00
async fn upload(paste: Data) -> Result<String, Debug<io::Error>> {
2016-12-10 03:56:49 +00:00
let id = PasteID::new(ID_LENGTH);
let filename = format!("upload/{id}", id = id);
let url = format!("{host}/{id}\n", host = HOST, id = id);
paste.stream_to_file(filename).await?;
Ok(url)
2016-12-10 03:56:49 +00:00
}
#[get("/<id>")]
async fn retrieve(id: PasteID<'_>) -> Option<Plain<File>> {
2016-12-10 03:56:49 +00:00
let filename = format!("upload/{id}", id = id);
File::open(&filename).await.map(Plain).ok()
2016-12-10 03:56:49 +00:00
}
#[get("/")]
fn index() -> &'static str {
"
USAGE
POST /
accepts raw data in the body of the request and responds with a URL of
a page containing the body's content
EXMAPLE: curl --data-binary @file.txt http://localhost:8000
GET /<id>
retrieves the content for the paste with id `<id>`
"
}
#[rocket::launch]
2017-04-14 21:39:17 +00:00
fn rocket() -> rocket::Rocket {
rocket::ignite().mount("/", routes![index, upload, retrieve])
}