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.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 mut context: HashMap<&str, Snippet> = HashMap::new();
  25. if let Ok(snippet) = snippet::get(&connection, id) {
  26. context.insert("snippet", snippet);
  27. }
  28. Template::render("snippets/show", &context)
  29. }
  30. #[get("/snippets/<id>/raw")]
  31. pub fn show_raw_snippet(id: i32, connection: DbConn) -> String {
  32. match snippet::get(&connection, id) {
  33. Ok(snippet) => snippet.body,
  34. Err(_) => String::from("Snippet not found"),
  35. }
  36. }
  37. #[post("/api/snippets", format = "application/json", data = "<snippet>")]
  38. pub fn create_snippet(
  39. snippet: Json<InsertableSnippet>,
  40. connection: DbConn,
  41. ) -> Result<status::Created<Json<Snippet>>, Status> {
  42. snippet::insert(snippet.into_inner(), &connection)
  43. .map(|snippet| status::Created(String::from(""), Some(Json(snippet))))
  44. .map_err(error_response)
  45. }
  46. #[catch(400)]
  47. pub fn bad_request(req: &Request) -> String {
  48. req.headers().get_one("content-length").map_or(
  49. String::from("{\"message\": \"Bad request\"}"),
  50. |length| {
  51. if length
  52. .parse::<i32>()
  53. .expect("Content length is non-numeric")
  54. > 1_000_000
  55. {
  56. String::from("{\"message\": \"Snippet must be under 1mb\"}")
  57. } else {
  58. String::from("{\"message\": \"Bad request\"}")
  59. }
  60. },
  61. )
  62. }