Skip to content

Commit

Permalink
improve logging of http errors
Browse files Browse the repository at this point in the history
  • Loading branch information
mxve committed Oct 2, 2023
1 parent b86d252 commit fddd146
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 13 deletions.
54 changes: 41 additions & 13 deletions src/http.rs
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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
));
}
}
}
8 changes: 8 additions & 0 deletions src/misc.rs
Original file line number Diff line number Diff line change
@@ -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());
Expand All @@ -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);
}

0 comments on commit fddd146

Please sign in to comment.