Rocket/examples/pastebin/src/main.rs

63 lines
1.3 KiB
Rust
Raw Normal View History

#![feature(plugin, decl_macro)]
2016-12-10 03:56:49 +00:00
#![plugin(rocket_codegen)]
extern crate rocket;
extern crate rand;
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 std::fs::File;
use std::path::Path;
use rocket::Data;
2016-12-10 05:01:30 +00:00
use rocket::response::content;
2016-12-10 03:56:49 +00:00
use paste_id::PasteID;
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>")]
fn upload(paste: Data) -> io::Result<String> {
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(Path::new(&filename))?;
Ok(url)
2016-12-10 03:56:49 +00:00
}
#[get("/<id>")]
2016-12-10 05:01:30 +00:00
fn retrieve(id: PasteID) -> Option<content::Plain<File>> {
2016-12-10 03:56:49 +00:00
let filename = format!("upload/{id}", id = id);
2016-12-10 05:01:30 +00:00
File::open(&filename).map(|f| content::Plain(f)).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>`
"
}
2017-04-14 21:39:17 +00:00
fn rocket() -> rocket::Rocket {
rocket::ignite().mount("/", routes![index, upload, retrieve])
}
2016-12-10 03:56:49 +00:00
fn main() {
2017-04-14 21:39:17 +00:00
rocket().launch();
2016-12-10 03:56:49 +00:00
}