Skip to content

Instantly share code, notes, and snippets.

@Inari-Whitebear
Last active August 29, 2015 14:13
Show Gist options
  • Save Inari-Whitebear/a00aea4724e13ef7dc1d to your computer and use it in GitHub Desktop.
Save Inari-Whitebear/a00aea4724e13ef7dc1d to your computer and use it in GitHub Desktop.
before:
fn get_file_contents(path: &str) -> Result<String, &'static str> {
let p = Path::new(BASE_PATH.to_string() + path);
let res: Result<String, &'static str>;
let file_result = File::open_mode(&p, Open, Read);
res = match file_result {
Ok(mut file) => {
let read_result_u8 = file.read_to_end();
match read_result_u8 {
Ok(read_data) => {
let read_result = std::str::from_utf8(&*read_data);
match read_result {
Ok(read_str) => {
Ok(read_str.to_string())
},
Err(_) => {
Err("500 Internal Server Error")
}
}
},
Err(_) => {
Err("500 Internal Server Error")
}
}
},
Err(_) => {
Err("404 File Not Found")
}
};
res
}
[...]
let file_result = get_file_contents(&**request.path.as_ref().unwrap());
match file_result {
Ok(dat) => {
data = dat;
status = "200 OK";
},
Err(err) => {
data = String::new();
status = err;
}
}
-------------------------------------
after:
fn get_file_contents(path: &str) -> IoResult<String> {
let p = Path::new(BASE_PATH.to_string() + path);
let mut file = try!(File::open_mode(&p, Open, Read));
let read_u8 = try!(file.read_to_end());
match std::str::from_utf8(&*read_u8) {
Ok(d) => { Ok(d.to_string()) },
Err(e) => { Err( std::io::IoError{ kind: std::io::IoErrorKind::OtherIoError, desc: "UTF-8 Conversion failed", detail: Some("Failed to convert read utf-8 data to &str".to_string()) } ) }
}
}
[...]
let file_result = get_file_contents(&**request.path.as_ref().unwrap());
match file_result {
Ok(dat) => {
data = dat;
status = "200 OK";
},
Err(err) => {
use std::io::IoErrorKind;
data = String::new();
status = match &err.kind {
&IoErrorKind::FileNotFound => web::errors::FILE_NOT_FOUND,
_ => web::errors::INTERNAL_ERROR
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment