The backend of a gist server written in Rust
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

routes.rs 2.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. #[post("/api/snippets", format = "application/json", data = "<snippet>")]
  41. pub fn create_snippet(
  42. snippet: Json<InsertableSnippet>,
  43. connection: DbConn,
  44. ) -> Result<status::Created<Json<Snippet>>, Status> {
  45. snippet::insert(snippet.into_inner(), &connection)
  46. .map(|snippet| status::Created(String::from(""), Some(Json(snippet))))
  47. .map_err(error_response)
  48. }
  49. #[catch(400)]
  50. pub fn bad_request(req: &Request) -> String {
  51. req.headers().get_one("content-length").map_or(
  52. String::from("{\"message\": \"Bad request\"}"),
  53. |length| {
  54. if length
  55. .parse::<i32>()
  56. .expect("Content length is non-numeric")
  57. > 1_000_000
  58. {
  59. String::from("{\"message\": \"Snippet must be under 1mb\"}")
  60. } else {
  61. String::from("{\"message\": \"Bad request\"}")
  62. }
  63. },
  64. )
  65. }