improve logging of http errors

This commit is contained in:
mxve 2023-10-02 04:39:49 +02:00
parent b86d252c4b
commit fddd146361
2 changed files with 49 additions and 13 deletions

View File

@ -1,20 +1,35 @@
use crate::misc;
use std::{fs, io::Write, path::Path, str};
pub fn get_body(url: &str) -> Vec<u8> {
let mut res: Vec<u8> = Vec::new();
let req = http_req::request::Request::new(&url.try_into().unwrap())
match http_req::request::Request::new(&url.try_into().unwrap())
.header(
"User-Agent",
"AlterWare Launcher | github.com/mxve/alterware-launcher",
)
.send(&mut res)
.unwrap_or_else(|error| {
panic!("\n\n{}:\n{:?}", "Error", error);
});
{
Ok(req) => {
if req.status_code() == http_req::response::StatusCode::new(302)
|| req.status_code() == http_req::response::StatusCode::new(301)
{
let location = req.headers().get("Location").unwrap().as_str();
return get_body(location);
}
if req.status_code() == http_req::response::StatusCode::new(302) {
let location = req.headers().get("Location").unwrap().as_str();
return get_body(location);
if req.status_code() != http_req::response::StatusCode::new(200) {
misc::fatal_error(&format!(
"Could not get body from {}, got {}",
url,
req.status_code()
));
}
}
Err(e) => {
misc::fatal_error(&format!("Could not get body from {}, got:\n{}", url, e));
}
}
res
@ -27,10 +42,23 @@ pub fn get_body_string(url: &str) -> String {
pub fn download_file(url: &str, file_path: &Path) {
let body = get_body(url);
let mut f = fs::File::create(file_path).unwrap_or_else(|error| {
panic!("\n\n{}:\n{:?}", "Error", error);
});
f.write_all(&body).unwrap_or_else(|error| {
panic!("\n\n{}:\n{:?}", "Error", error);
});
match fs::File::create(file_path) {
Ok(mut file) => match file.write_all(&body) {
Ok(_) => (),
Err(e) => {
misc::fatal_error(&format!(
"Could not write to file {}, got:\n{}",
file_path.to_str().unwrap(),
e
));
}
},
Err(e) => {
misc::fatal_error(&format!(
"Could not create file {}, got:\n{}",
file_path.to_str().unwrap(),
e
));
}
}
}

View File

@ -1,5 +1,7 @@
use std::{fs, path::PathBuf};
use colored::Colorize;
pub fn get_file_sha1(path: &PathBuf) -> String {
let mut sha1 = sha1_smol::Sha1::new();
sha1.update(&fs::read(path).unwrap());
@ -18,3 +20,9 @@ pub fn rev_to_int(rev: &str) -> u16 {
.parse::<u16>()
.unwrap_or(0)
}
pub fn fatal_error(error: &str) {
println!("\n\n{}:\n{}", "Error".bright_red(), error);
stdin();
std::process::exit(1);
}