1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
use std::fmt::Display;
use http::StatusCode;
use serde::Serialize;
use crate::{InputSource, Status, Uri};
/// Response type returned by lychee after checking a URI
#[derive(Debug)]
pub struct Response(pub InputSource, pub ResponseBody);
impl Response {
#[inline]
#[must_use]
/// Create new response
pub const fn new(uri: Uri, status: Status, source: InputSource) -> Self {
Response(source, ResponseBody { uri, status })
}
#[inline]
#[must_use]
/// Retrieve the underlying status of the response
pub const fn status(&self) -> &Status {
&self.1.status
}
}
impl Display for Response {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
<ResponseBody as Display>::fmt(&self.1, f)
}
}
impl Serialize for Response {
fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
<ResponseBody as Serialize>::serialize(&self.1, s)
}
}
#[allow(clippy::module_name_repetitions)]
#[derive(Debug, Serialize, Hash, PartialEq, Eq)]
/// Encapsulates the state of a URI check
pub struct ResponseBody {
#[serde(flatten)]
/// The URI which was checked
pub uri: Uri,
/// The status of the check
pub status: Status,
}
// Extract as much information from the underlying error conditions as possible
// without being too verbose. Some dependencies (rightfully) don't expose all
// error fields to downstream crates, which is why we have to defer to pattern
// matching in these cases.
impl Display for ResponseBody {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{} [{}] {}",
self.status.icon(),
self.status.code_as_string(),
self.uri
)?;
if let Status::Ok(StatusCode::OK) = self.status {
// Don't print anything else if the status code is 200.
// The output gets too verbose then.
return Ok(());
}
// Add a separator between the URI and the additional details below.
// Note: To make the links clickable in some terminals,
// we add a space before the separator.
write!(f, " | {}", self.status)?;
if let Some(details) = self.status.details() {
write!(f, ": {details}")
} else {
Ok(())
}
}
}