Initial json parsing
This commit is contained in:
parent
c2fe292b2d
commit
1667e14d64
3 changed files with 32 additions and 5 deletions
1
.gitignore
vendored
1
.gitignore
vendored
|
@ -1 +1,2 @@
|
||||||
/target
|
/target
|
||||||
|
names.json
|
||||||
|
|
|
@ -10,10 +10,8 @@ use names::Site;
|
||||||
|
|
||||||
#[launch]
|
#[launch]
|
||||||
fn rocket() -> _ {
|
fn rocket() -> _ {
|
||||||
let names = vec![
|
let names_file = std::fs::File::open("names.json").unwrap();
|
||||||
Site::new("mossfet.xyz", Some("Mossy's site")),
|
let names = names::load_names(names_file).unwrap();
|
||||||
Site::new("fries.gay", Some("Fries's site"))
|
|
||||||
];
|
|
||||||
rocket::build()
|
rocket::build()
|
||||||
.manage(names)
|
.manage(names)
|
||||||
.mount(
|
.mount(
|
||||||
|
|
30
src/names.rs
30
src/names.rs
|
@ -1,6 +1,8 @@
|
||||||
use std::fs::File;
|
use std::fs::File;
|
||||||
use std::io::{BufReader, Read};
|
use std::io::{BufReader, Read};
|
||||||
|
use serde_json::{Map, Value};
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
pub enum NamesError {
|
pub enum NamesError {
|
||||||
FileAccessError,
|
FileAccessError,
|
||||||
ParseError,
|
ParseError,
|
||||||
|
@ -8,13 +10,39 @@ pub enum NamesError {
|
||||||
|
|
||||||
pub fn load_names(names_file: File) -> Result<Vec<Site>, NamesError> {
|
pub fn load_names(names_file: File) -> Result<Vec<Site>, NamesError> {
|
||||||
let mut buf_reader = BufReader::new(names_file);
|
let mut buf_reader = BufReader::new(names_file);
|
||||||
|
let mut output: Vec<Site> = vec![];
|
||||||
let mut contents = String::new();
|
let mut contents = String::new();
|
||||||
match buf_reader.read_to_string(&mut contents) {
|
match buf_reader.read_to_string(&mut contents) {
|
||||||
Ok(_) => {},
|
Ok(_) => {},
|
||||||
Err(_) => {return Err(NamesError::FileAccessError)},
|
Err(_) => {return Err(NamesError::FileAccessError)},
|
||||||
}
|
}
|
||||||
|
|
||||||
println!("{}", contents);
|
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 {
|
pub struct Site {
|
||||||
|
|
Loading…
Reference in a new issue