The backend of a gist server written in Rust
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

routes.rs 1.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. use diesel::result::Error;
  2. use rocket::http::Status;
  3. use rocket::response::status;
  4. use rocket_contrib::json::Json;
  5. use rocket_contrib::templates::Template;
  6. use std::collections::HashMap;
  7. use crate::connection::DbConn;
  8. use crate::gists;
  9. use crate::gists::{Gist, InsertableGist};
  10. fn error_response(error: Error) -> Status {
  11. match error {
  12. Error::NotFound => Status::NotFound,
  13. _ => Status::InternalServerError,
  14. }
  15. }
  16. #[get("/")]
  17. pub fn index() -> Template {
  18. let context: HashMap<&str, String> = HashMap::new();
  19. Template::render("index", &context)
  20. }
  21. #[get("/gists/<id>")]
  22. pub fn show_gist(id: i32, connection: DbConn) -> Template {
  23. let result = match gists::get(&connection, id) {
  24. Ok(gist) => Some(gist),
  25. Err(_) => None,
  26. };
  27. let (title, body) = result.map_or(
  28. (
  29. String::from("404 - Gist not found"),
  30. format!("<h3'>{}</h3>", "Gist not found"),
  31. ),
  32. |gist| (gist.title, gist.formatted_body),
  33. );
  34. let mut context: HashMap<&str, String> = HashMap::new();
  35. context.insert("title", title);
  36. context.insert("body", body);
  37. Template::render("gists/show", &context)
  38. }
  39. #[post("/api/gists", format = "application/json", data = "<gist>")]
  40. pub fn create_gist<'a>(
  41. gist: Json<InsertableGist>,
  42. connection: DbConn,
  43. ) -> Result<status::Created<Json<Gist>>, Status> {
  44. gists::insert(gist.into_inner(), &connection)
  45. .map(|gist| status::Created(String::from(""), Some(Json(gist))))
  46. .map_err(|error| error_response(error))
  47. }