mirror of https://git.sr.ht/~slondr/spart
actually handle connection errors
This commit is contained in:
parent
ce01b82533
commit
739e875117
29
src/lib.rs
29
src/lib.rs
|
@ -35,7 +35,6 @@ impl Request {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
impl std::fmt::Display for Request {
|
impl std::fmt::Display for Request {
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
|
||||||
write!(f, "{} {} {}\r\n{}", self.host, self.path, self.content_length, match &self.data {
|
write!(f, "{} {} {}\r\n{}", self.host, self.path, self.content_length, match &self.data {
|
||||||
|
@ -49,20 +48,26 @@ pub fn get(r: String) -> Result<String, &'static str> {
|
||||||
match Url::parse(&r) {
|
match Url::parse(&r) {
|
||||||
Err(_) => Err("Cannot parse url"),
|
Err(_) => Err("Cannot parse url"),
|
||||||
Ok(url) => {
|
Ok(url) => {
|
||||||
let port = url.port_or_known_default().unwrap(); // patched version of `uri` DOES have a default
|
if let Some(port) = url.port_or_known_default() { // patched version of `uri` DOES have a default
|
||||||
let request = Request::from_url(url)?;
|
let request = Request::from_url(url)?;
|
||||||
let mut connection = std::net::TcpStream::connect(format!("{}:{}", request.host, port)).unwrap();
|
if let Ok(mut connection) = std::net::TcpStream::connect(format!("{}:{}", request.host, port)) {
|
||||||
let request_string = request.to_string();
|
let request_string = request.to_string();
|
||||||
|
|
||||||
match connection.write_all(request_string.as_bytes()) {
|
match connection.write_all(request_string.as_bytes()) {
|
||||||
Err(_) => Err("Error writing to socket"),
|
Err(_) => Err("Error writing to socket"),
|
||||||
Ok(()) => {
|
Ok(()) => {
|
||||||
let mut buffer = String::new();
|
let mut buffer = String::new();
|
||||||
match connection.read_to_string(&mut buffer) {
|
match connection.read_to_string(&mut buffer) {
|
||||||
Err(_) => Err("Unable to read response"),
|
Err(_) => Err("Unable to read response"),
|
||||||
Ok(_) => Ok(buffer)
|
Ok(_) => Ok(buffer)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
Err("Failed to connect to host")
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
Err("Could not figure out port")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue