main.rs 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. #![feature(plugin, decl_macro)]
  2. #![plugin(rocket_codegen)]
  3. #[macro_use] extern crate rocket;
  4. #[macro_use] extern crate lazy_static;
  5. #[macro_use] extern crate json;
  6. extern crate rocket_cors;
  7. #[macro_use]
  8. extern crate serde_json;
  9. extern crate json_patch;
  10. use std::io::prelude::*;
  11. use std::fs::File;
  12. use std::path::{Path, PathBuf};
  13. use std::thread;
  14. use std::time::Duration;
  15. use std::sync::Mutex;
  16. use rocket::response::NamedFile;
  17. use json_patch::patch;
  18. use serde_json::from_str;
  19. use serde_json::to_string;
  20. use json_patch::merge;
  21. lazy_static! {
  22. static ref OBJECT: Mutex<String> = Mutex::new(String::from("{}"));
  23. }
  24. // send out the stored object
  25. #[get("/")]
  26. fn get() -> String {
  27. match OBJECT.lock() {
  28. Ok(obj) => {
  29. println!("MATCH obj {:?}", *obj);
  30. let result: &String = &*obj;
  31. result.clone()
  32. },
  33. _ => {
  34. println!("UNLOCK failed");
  35. String::from("{}")
  36. }
  37. }
  38. }
  39. //set the storage
  40. #[get("/<obj>")]
  41. fn set(obj: String) -> String {
  42. // let json_result = json::parse(obj.to_owned().as_str());
  43. // let json_result: serde_json::Value = from_str(obj.to_owned().as_str());
  44. let json_result: Result<serde_json::Value, serde_json::Error> = from_str(obj.to_owned().as_str());
  45. match json_result {
  46. Ok(json_from_web) => {
  47. let mut locked_obj = OBJECT.lock().unwrap();
  48. // let current_object = json::parse(&locked_obj);
  49. let mut parsed_object: Result<serde_json::Value, serde_json::Error> = from_str(&locked_obj);
  50. match parsed_object {
  51. Ok(mut json_object) => {
  52. println!("{:?}", json_object);
  53. merge(&mut json_object, &json_from_web);
  54. *locked_obj = to_string(&json_object).unwrap();
  55. println!("JSON MERGE {:?}", json_object);
  56. },
  57. Err(e) => {
  58. // The db is somehow corrupted, just put in what we got from the web
  59. println!("Invalid json in db {:?}", e);
  60. *locked_obj = to_string(&json_from_web).unwrap();
  61. }
  62. }
  63. println!("GOT {:?}", obj);
  64. println!("JSON INCOMING {:?}", json_from_web);
  65. String::from("Done")
  66. },
  67. Err(_e) => String::from("Invalid Json")
  68. }
  69. }
  70. // Static file serving
  71. #[get("/<file..>")]
  72. fn static_content(file: PathBuf) -> NamedFile {
  73. let f = NamedFile::open(Path::new("static/").join(file));
  74. match f {
  75. Ok(result) => result,
  76. Err(_e) => NamedFile::open("static/err.html").unwrap()
  77. }
  78. }
  79. // periodically dump the database
  80. fn disk_committer() {
  81. thread::spawn(|| {
  82. loop {
  83. thread::sleep(Duration::from_secs(2));
  84. match OBJECT.lock() {
  85. Ok(obj) => {
  86. let result: &String = &*obj;
  87. let mut buffer = File::create("db").unwrap();
  88. buffer.write(result.as_bytes()).unwrap();
  89. // println!("Committing to disk");
  90. },
  91. _ => ()
  92. }
  93. }
  94. });
  95. }
  96. fn read_db() {
  97. let dbfile = File::open("db");
  98. match dbfile {
  99. Ok(mut f) => {
  100. let mut contents = String::new();
  101. f.read_to_string(&mut contents).expect("{}");
  102. let mut data = OBJECT.lock().unwrap();
  103. *data = contents;
  104. },
  105. Err(e) => println!("Could not load db file {:?}", e)
  106. }
  107. }
  108. fn main() {
  109. // let (allowed_origins, failed_origins) = AllowedOrigins::some(&["https://www.acme.com"]);
  110. // assert!(failed_origins.is_empty());
  111. // // You can also deserialize this
  112. // let options = rocket_cors::Cors {
  113. // allowed_origins: allowed_origins,
  114. // allowed_methods: vec![Method::Get].into_iter().map(From::from).collect(),
  115. // allowed_headers: AllowedHeaders::some(&["Authorization", "Accept"]),
  116. // allow_credentials: true,
  117. // ..Default::default()
  118. // };
  119. // let default = rocket_cors::Cors::default();
  120. // Load from db
  121. read_db();
  122. disk_committer();
  123. rocket::ignite()
  124. .mount("/set", routes![set])
  125. .mount("/get", routes![get])
  126. // .mount("/test", routes![test])
  127. .mount("/static", routes![static_content])
  128. // .attach(default)
  129. .launch();
  130. }