routes: implement syntax highlighting for plaintext files
Signed-off-by: Gunwant Jain <mail@wantguns.dev>
This commit is contained in:
33
src/main.rs
33
src/main.rs
@@ -3,12 +3,12 @@
|
||||
|
||||
extern crate tree_magic;
|
||||
|
||||
use std::io;
|
||||
use std::io::prelude::*;
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use std::fs::File;
|
||||
|
||||
use rocket::Data;
|
||||
use rocket::http::RawStr;
|
||||
use rocket_contrib::templates::Template;
|
||||
|
||||
mod paste_id;
|
||||
@@ -16,12 +16,23 @@ mod paste_id;
|
||||
use paste_id::PasteId;
|
||||
|
||||
#[get("/p/<id>")]
|
||||
fn pretty_retrieve(id: PasteId) -> Option<File> {
|
||||
fn pretty_retrieve(id: PasteId) -> Option<Template> {
|
||||
let filename = format!("upload/{id}", id = id);
|
||||
let filepath = Path::new(&filename);
|
||||
let mut file = File::open(&filename).unwrap();
|
||||
|
||||
let mut contents = String::new();
|
||||
file.read_to_string(&mut contents).unwrap();
|
||||
let theme = String::from(".");
|
||||
|
||||
let mut map = HashMap::new();
|
||||
map.insert("title", id.to_string());
|
||||
map.insert("theme", theme);
|
||||
map.insert("code", contents);
|
||||
let rendered = Template::render("pretty", &map);
|
||||
|
||||
match tree_magic::from_filepath(filepath).as_str() {
|
||||
"text/plain" => File::open(&filename).ok(),
|
||||
"text/plain" => Some(rendered),
|
||||
_ => Err("does not have the MIME type of a plaintext file").ok()
|
||||
}
|
||||
}
|
||||
@@ -36,10 +47,17 @@ fn retrieve(id: PasteId) -> Option<File> {
|
||||
#[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))?;
|
||||
let filename = format!("upload/{id}", id = id);
|
||||
let filepath = Path::new(&filename);
|
||||
|
||||
paste.stream_to_file(filepath)?;
|
||||
|
||||
let url = match tree_magic::from_filepath(filepath).as_str() {
|
||||
"text/plain" => format!("{host}/p/{id}\n", host = "http://localhost:8000", id = id),
|
||||
_ => format!("{host}/{id}\n", host = "http://localhost:8000", id = id),
|
||||
};
|
||||
|
||||
Ok(url)
|
||||
}
|
||||
|
||||
@@ -67,5 +85,6 @@ USAGE
|
||||
fn main() {
|
||||
rocket::ignite()
|
||||
.mount("/", routes![index, upload, retrieve, pretty_retrieve])
|
||||
.attach(Template::fairing())
|
||||
.launch();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user