first experiments with rocket

This commit is contained in:
2019-12-29 15:00:59 +01:00
commit a1b8f5a1a1
9 changed files with 1436 additions and 0 deletions
+39
View File
@@ -0,0 +1,39 @@
#![feature(proc_macro_hygiene, decl_macro)]
#[macro_use] extern crate rocket;
#[macro_use] extern crate serde;
//use rocket::request::FromSegments;
//use rocket::http::uri::Segments;
//use rocket_contrib::serve::StaticFiles;
use rocket_contrib::templates::Template;
mod store;
use crate::store::Store;
use rocket::State;
use parking_lot::RwLock;
use rocket::response::Redirect;
use rocket::http::Status;
use rocket::request::Form;
use std::collections::HashMap;
#[get("/")]
fn index(store : State<RwLock<Store>>) -> Template {
let mut context = HashMap::new();
let rg = store.read();
context.insert("records", &rg.parts);
Template::render("index", context)
}
#[post("/add", data="<record>")]
fn add_part(store : State<RwLock<Store>>, record : Form<store::Part>) -> Redirect {
store.write().add(record.into_inner());
Redirect::to(uri!(index))
}
fn main() {
rocket::ignite()
.attach(Template::fairing())
.manage(RwLock::new(Store::new()))
.mount("/", routes![index, add_part]).launch();
}
+52
View File
@@ -0,0 +1,52 @@
use std::fs::{File, OpenOptions};
use std::io::{Read, Write, Error};
use std::path::Path;
use rocket::request::FromForm;
#[derive(Serialize,Deserialize)]
pub struct Store {
pub parts : Vec<Part>
}
#[derive(Serialize,Deserialize,FromForm)]
pub struct Part {
name : String,
quantity : usize,
location : String,
}
fn load_file_or(file : impl AsRef<Path>, def : String) -> String {
let mut file = match File::open(file) {
Ok(file) => file,
Err(_) => return def
};
let mut buf = String::new();
if file.read_to_string(&mut buf).is_err() {
return def;
}
buf
}
impl Store {
pub fn new() -> Self {
let mut file = load_file_or("inventory.json", "[]".to_string());
Store {
parts: serde_json::from_str(&file).unwrap(),
}
}
pub fn add(&mut self, part : Part) {
self.parts.push(part);
self.persist()
}
pub fn persist(&self) {
let mut file = OpenOptions::new().write(true).create(true).truncate(true).open("inventory.json").unwrap();
file.write(serde_json::to_string(&self.parts).unwrap().as_bytes()).unwrap();
}
}