microformats/
http.rs

1#![cfg(feature = "http")]
2
3use crate::types::Document;
4use http::{header::CONTENT_TYPE, HeaderValue, Response};
5
6pub type Body = Vec<u8>;
7
8/// Converts [this response][::http::Response] into a [MF2 document][microformats::types::Document].
9///
10/// # Errors
11///
12/// This function will return an error if it could not detect the content type of this request or
13/// fails to convert it into a MF2 document.
14pub fn to_mf2_document(resp: Response<Body>, page_url: &str) -> Result<Document, crate::Error> {
15    let ct_header = resp
16        .headers()
17        .get(CONTENT_TYPE)
18        .cloned()
19        .unwrap_or_else(|| HeaderValue::from_static("text/html"))
20        .as_ref()
21        .to_vec();
22
23    let ct_header_str = String::from_utf8(ct_header)?;
24
25    if ct_header_str.starts_with("application/mf2+json") {
26        to_json(resp)
27            .and_then(|v| Ok(serde_json::from_value(v).map_err(microformats_types::Error::from)?))
28    } else {
29        to_string(resp).and_then(|str| crate::from_html(&str, &page_url.parse()?))
30    }
31}
32
33fn to_string(resp: Response<Body>) -> Result<String, crate::Error> {
34    Ok(String::from_utf8(resp.into_body())?)
35}
36
37fn to_json(resp: Response<Body>) -> Result<serde_json::Value, crate::Error> {
38    Ok(serde_json::from_slice(resp.into_body().as_slice())
39        .map_err(microformats_types::Error::from)?)
40}