Simplifies HTTP client code

pull/171/head
Tpt 3 years ago
parent 311fffe711
commit 083c16eaa9
  1. 45
      lib/src/sparql/http/simple.rs

@ -3,8 +3,6 @@ use oxhttp::model::{Body, HeaderName, Method, Request};
use std::io::Result;
use std::time::Duration;
const USER_AGENT: &str = concat!("Oxigraph/", env!("CARGO_PKG_VERSION"));
pub struct Client {
client: oxhttp::Client,
}
@ -13,23 +11,20 @@ impl Client {
pub fn new(timeout: Option<Duration>) -> Self {
let mut client = oxhttp::Client::new();
client.set_global_timeout(timeout);
client
.set_user_agent(concat!("Oxigraph/", env!("CARGO_PKG_VERSION")).into())
.unwrap();
Self { client }
}
pub fn get(&self, url: &str, accept: &str) -> Result<(String, Body)> {
let mut request = Request::new(Method::GET, url.parse().map_err(invalid_input_error)?);
request.headers_mut().append(
HeaderName::ACCEPT,
accept.parse().map_err(invalid_input_error)?,
);
request.headers_mut().append(
HeaderName::USER_AGENT,
USER_AGENT.parse().map_err(invalid_input_error)?,
);
let request = Request::builder(Method::GET, url.parse().map_err(invalid_input_error)?)
.with_header(HeaderName::ACCEPT, accept)
.map_err(invalid_input_error)?
.build();
let response = self.client.request(request)?;
let content_type = response
.headers()
.get(&HeaderName::CONTENT_TYPE)
.header(&HeaderName::CONTENT_TYPE)
.ok_or_else(|| invalid_data_error(format!("No Content-Type returned by {}", url)))?
.to_str()
.map_err(invalid_data_error)?
@ -44,23 +39,15 @@ impl Client {
content_type: &str,
accept: &str,
) -> Result<(String, Body)> {
let mut request = Request::new(Method::GET, url.parse().map_err(invalid_input_error)?);
request.headers_mut().append(
HeaderName::ACCEPT,
accept.parse().map_err(invalid_input_error)?,
);
request.headers_mut().append(
HeaderName::USER_AGENT,
USER_AGENT.parse().map_err(invalid_input_error)?,
);
request.headers_mut().append(
HeaderName::CONTENT_TYPE,
content_type.parse().map_err(invalid_input_error)?,
);
let response = self.client.request(request.with_body(payload))?;
let request = Request::builder(Method::GET, url.parse().map_err(invalid_input_error)?)
.with_header(HeaderName::ACCEPT, accept)
.map_err(invalid_input_error)?
.with_header(HeaderName::CONTENT_TYPE, content_type)
.map_err(invalid_input_error)?
.with_body(payload);
let response = self.client.request(request)?;
let content_type = response
.headers()
.get(&HeaderName::CONTENT_TYPE)
.header(&HeaderName::CONTENT_TYPE)
.ok_or_else(|| invalid_data_error(format!("No Content-Type returned by {}", url)))?
.to_str()
.map_err(invalid_data_error)?

Loading…
Cancel
Save