Add pastebin example.

This commit is contained in:
Sergio Benitez 2016-12-09 19:56:49 -08:00
parent d0136235d7
commit e0bc546e93
5 changed files with 116 additions and 0 deletions

View File

@ -27,4 +27,5 @@ members = [
"examples/config",
"examples/hello_alt_methods",
"examples/raw_upload",
"examples/pastebin",
]

View File

@ -0,0 +1,10 @@
[package]
name = "pastebin"
version = "0.0.1"
authors = ["Sergio Benitez <sb@sergio.bz>"]
workspace = "../../"
[dependencies]
rocket = { path = "../../lib" }
rocket_codegen = { path = "../../codegen" }
rand = "0.3"

View File

@ -0,0 +1,58 @@
#![feature(plugin)]
#![plugin(rocket_codegen)]
extern crate rocket;
extern crate rand;
mod paste_id;
use std::io;
use std::fs::File;
use std::path::Path;
use rocket::Data;
use rocket::response::{content, Failure};
use rocket::http::StatusCode::NotFound;
use paste_id::PasteID;
const HOST: &'static str = "http://localhost:8000";
const ID_LENGTH: usize = 3;
#[post("/", data = "<paste>")]
fn upload(paste: Data) -> io::Result<content::Plain<String>> {
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(content::Plain(url))
}
#[get("/<id>")]
fn retrieve(id: PasteID) -> Result<content::Plain<File>, Failure> {
let filename = format!("upload/{id}", id = id);
File::open(&filename).map(|f| content::Plain(f)).map_err(|_| Failure(NotFound))
}
#[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>`
"
}
fn main() {
rocket::ignite().mount("/", routes![index, upload, retrieve]).launch()
}

View File

@ -0,0 +1,47 @@
use std::fmt;
use std::borrow::Cow;
use rocket::request::FromParam;
use rand::{self, Rng};
const BASE62: &'static [u8] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
fn valid_id(id: &str) -> bool {
id.chars().all(|c| {
(c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')
})
}
pub struct PasteID<'a>(Cow<'a, str>);
impl<'a> PasteID<'a> {
/// Here's how this works: get `size` random 8-bit integers, convert them
/// into base-62 characters, and concat them to get the ID.
pub fn new(size: usize) -> PasteID<'static> {
let mut id = String::with_capacity(size);
let mut rng = rand::thread_rng();
for _ in 0..size {
id.push(BASE62[rng.gen::<usize>() % 62] as char);
}
PasteID(Cow::Owned(id))
}
}
impl<'a> FromParam<'a> for PasteID<'a> {
type Error = &'a str;
fn from_param(param: &'a str) -> Result<PasteID<'a>, &'a str> {
match valid_id(param) {
true => Ok(PasteID(Cow::Borrowed(param))),
false => Err(param)
}
}
}
impl<'a> fmt::Display for PasteID<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0)
}
}

View File