Initial json parsing

This commit is contained in:
Mossfet 2023-06-30 17:47:25 +01:00
parent c2fe292b2d
commit 1667e14d64
3 changed files with 32 additions and 5 deletions

1
.gitignore vendored
View file

@ -1 +1,2 @@
/target
names.json

View file

@ -10,10 +10,8 @@ use names::Site;
#[launch]
fn rocket() -> _ {
let names = vec![
Site::new("mossfet.xyz", Some("Mossy's site")),
Site::new("fries.gay", Some("Fries's site"))
];
let names_file = std::fs::File::open("names.json").unwrap();
let names = names::load_names(names_file).unwrap();
rocket::build()
.manage(names)
.mount(

View file

@ -1,6 +1,8 @@
use std::fs::File;
use std::io::{BufReader, Read};
use serde_json::{Map, Value};
#[derive(Debug)]
pub enum NamesError {
FileAccessError,
ParseError,
@ -8,13 +10,39 @@ pub enum NamesError {
pub fn load_names(names_file: File) -> Result<Vec<Site>, NamesError> {
let mut buf_reader = BufReader::new(names_file);
let mut output: Vec<Site> = vec![];
let mut contents = String::new();
match buf_reader.read_to_string(&mut contents) {
Ok(_) => {},
Err(_) => {return Err(NamesError::FileAccessError)},
}
println!("{}", contents);
Err(NamesError::ParseError)
match serde_json::from_str(&contents) {
Ok(Value::Array(sites_array)) => {
for i in sites_array {
match i {
Value::Object(site) => {
let url = site.get("url");
let name = site.get("name");
match (url, name) {
(Some(Value::String(url)), Some(Value::String(name))) => {
output.push(Site::new(url, Some(name)));
},
(Some(Value::String(url)), None) => {
output.push(Site::new(url, None));
},
_ => {return Err(NamesError::ParseError)},
};
}
_ => {return Err(NamesError::ParseError)}
}
}
}
_ => {return Err(NamesError::ParseError)}
}
Ok(output)
}
pub struct Site {