initialise

routes:
    GET  /<id>
    POST /

Signed-off-by: Gunwant Jain <mail@wantguns.dev>
This commit is contained in:
Gunwant Jain
2020-12-29 15:44:15 +05:30
commit 805e4ce7d2
6 changed files with 951 additions and 0 deletions

53
src/main.rs Normal file
View File

@@ -0,0 +1,53 @@
#![feature(proc_macro_hygiene, decl_macro)]
#[macro_use] extern crate rocket;
use std::io;
use std::path::Path;
use std::fs::File;
use rocket::Data;
use rocket::http::RawStr;
mod paste_id;
use paste_id::PasteId;
#[get("/<id>")]
fn retrieve(id: PasteId) -> Option<File> {
let filename = format!("upload/{id}", id = id);
File::open(&filename).ok()
}
#[post("/", data = "<paste>")]
fn upload(paste: Data) -> Result<String, std::io::Error> {
let id = PasteId::new(4);
let filename = format!("upload/{id}", id = id);
let url = format!("{host}/{id}\n", host = "http://localhost:8000", id = id);
paste.stream_to_file(Path::new(&filename))?;
Ok(url)
}
#[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
GET /<id>
retrieves the content for the paste with id `<id>`
"
}
fn main() {
rocket::ignite()
.mount("/", routes![index, upload, retrieve])
.launch();
}

42
src/paste_id.rs Normal file
View File

@@ -0,0 +1,42 @@
use std::borrow::Cow;
use std::fmt;
use rocket::http::RawStr;
use rocket::request::FromParam;
use rand::{self, distributions::Alphanumeric, Rng};
pub struct PasteId<'a>(Cow<'a, str>);
fn valid_id(id: &str) -> bool {
id.chars().all(char::is_alphanumeric)
}
impl<'a> PasteId<'a> {
pub fn new(size: usize) -> PasteId<'static> {
let id: String = rand::thread_rng()
.sample_iter(&Alphanumeric)
.take(size)
.map(char::from)
.collect();
PasteId(Cow::Owned(id))
}
}
impl<'a> FromParam<'a> for PasteId<'a> {
type Error = &'a RawStr;
fn from_param(param: &'a RawStr) -> Result<Self, Self::Error> {
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)
}
}