The backend of a gist server written in Rust
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

routes.rs 2.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 syntect::highlighting::ThemeSet;
  8. use syntect::html::highlighted_html_for_string;
  9. use syntect::parsing::SyntaxSet;
  10. use crate::connection::DbConn;
  11. use crate::gists;
  12. use crate::gists::{Gist, InsertableGist};
  13. fn error_response(error: Error) -> Status {
  14. match error {
  15. Error::NotFound => Status::NotFound,
  16. _ => Status::InternalServerError,
  17. }
  18. }
  19. #[get("/")]
  20. pub fn index(connection: DbConn) -> Result<Json<Vec<Gist>>, Status> {
  21. gists::all(&connection)
  22. .map(|gists| Json(gists))
  23. .map_err(|error| error_response(error))
  24. }
  25. #[get("/gists/<id>")]
  26. pub fn show_gist(id: i32, connection: DbConn) -> Template {
  27. let gist = match gists::get(&connection, id) {
  28. Ok(gist) => Some(gist),
  29. Err(_) => None,
  30. };
  31. let mut context = HashMap::new();
  32. match gist {
  33. Some(g) => {
  34. let body = match g.filetype {
  35. Some(filetype) => {
  36. let ps = SyntaxSet::load_defaults_newlines();
  37. let ts = ThemeSet::load_defaults();
  38. let syntax = ps.find_syntax_by_extension(&filetype);
  39. match syntax {
  40. Some(s) => highlighted_html_for_string(
  41. &g.body,
  42. &ps,
  43. s,
  44. &ts.themes["Solarized (light)"],
  45. ),
  46. None => format!("<pre class='plaintext'>{}</pre>", g.body),
  47. }
  48. }
  49. None => format!("<pre class='plaintext'>{}</pre>", g.body),
  50. };
  51. context.insert("title", g.title.clone());
  52. context.insert("body", body);
  53. }
  54. None => {
  55. context.insert("title", "404".to_string());
  56. context.insert("body", "<h3>Gist not found</h3>".to_string());
  57. }
  58. }
  59. Template::render("gists/show", &context)
  60. }
  61. #[post("/api/gists", format = "application/json", data = "<gist>")]
  62. pub fn create_gist<'a>(
  63. gist: Json<InsertableGist>,
  64. connection: DbConn,
  65. ) -> Result<status::Created<Json<Gist>>, Status> {
  66. gists::insert(gist.into_inner(), &connection)
  67. .map(|gist| status::Created(String::from(""), Some(Json(gist))))
  68. .map_err(|error| error_response(error))
  69. }