The backend of a gist server written in Rust
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

routes.rs 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. use diesel::result::Error;
  2. use rocket::http::Status;
  3. use rocket::request::Request;
  4. use rocket::response::status;
  5. use rocket_contrib::json::Json;
  6. use rocket_contrib::templates::Template;
  7. use std::collections::HashMap;
  8. use crate::connection::DbConn;
  9. use crate::snippet;
  10. use crate::snippet::{InsertableSnippet, Snippet};
  11. fn error_response(error: Error) -> Status {
  12. match error {
  13. Error::NotFound => Status::NotFound,
  14. _ => Status::InternalServerError,
  15. }
  16. }
  17. #[get("/")]
  18. pub fn index() -> Template {
  19. let context: HashMap<&str, String> = HashMap::new();
  20. Template::render("index", &context)
  21. }
  22. #[get("/snippets/<id>")]
  23. pub fn show_snippet(id: i32, connection: DbConn) -> Template {
  24. let result = match snippet::get(&connection, id) {
  25. Ok(snippet) => Some(snippet),
  26. Err(_) => None,
  27. };
  28. let (title, body) = result.map_or(
  29. (
  30. String::from("404 - Snippet not found"),
  31. format!("<h3'>{}</h3>", "Snippet not found"),
  32. ),
  33. |snippet| (snippet.title, snippet.formatted_body),
  34. );
  35. let mut context: HashMap<&str, String> = HashMap::new();
  36. context.insert("title", title);
  37. context.insert("body", body);
  38. Template::render("snippets/show", &context)
  39. }
  40. #[get("/snippets/<id>/raw")]
  41. pub fn show_raw_snippet(id: i32, connection: DbConn) -> String {
  42. let result = match snippet::get(&connection, id) {
  43. Ok(snippet) => Some(snippet),
  44. Err(_) => None,
  45. };
  46. result.map_or(String::from("Snippet not found"), |snippet| snippet.body)
  47. }
  48. #[post("/api/snippets", format = "application/json", data = "<snippet>")]
  49. pub fn create_snippet(
  50. snippet: Json<InsertableSnippet>,
  51. connection: DbConn,
  52. ) -> Result<status::Created<Json<Snippet>>, Status> {
  53. snippet::insert(snippet.into_inner(), &connection)
  54. .map(|snippet| status::Created(String::from(""), Some(Json(snippet))))
  55. .map_err(error_response)
  56. }
  57. #[catch(400)]
  58. pub fn bad_request(req: &Request) -> String {
  59. req.headers().get_one("content-length").map_or(
  60. String::from("{\"message\": \"Bad request\"}"),
  61. |length| {
  62. if length
  63. .parse::<i32>()
  64. .expect("Content length is non-numeric")
  65. > 1_000_000
  66. {
  67. String::from("{\"message\": \"Snippet must be under 1mb\"}")
  68. } else {
  69. String::from("{\"message\": \"Bad request\"}")
  70. }
  71. },
  72. )
  73. }