use curl::http;
use serde::Deserialize;
use serde_json;
use std::fmt;
pub fn parse_response<S, F>(resp: http::Response, on_success: S, on_failure: F) -> ::EdgeGridResult
where S: Fn(String) -> ::EdgeGridResult,
F: Fn(String) -> ::EdgeGridResult
{
let body_vec = Vec::from(resp.get_body());
let body = try!(String::from_utf8(body_vec));
match resp.get_code() {
c @ 200...299 => {
debug!("Successful 2xx: {}", c);
debug!("Content-Length Check: {}", check_content_length(&resp));
debug!("Content-Type Check: {}", check_content_type_json(&resp));
on_success(body)
}
c @ 300...399 => {
debug!("Redirection 3xx: {}", c);
debug!("Content-Length Check: {}", check_content_length(&resp));
debug!("Content-Type Check: {}",
check_content_type_problem_json(&resp));
on_failure(body)
}
c @ 400...499 => {
debug!("Client Error 4xx: {}", c);
debug!("Content-Length Check: {}", check_content_length(&resp));
debug!("Content-Type Check: {}",
check_content_type_problem_json(&resp));
on_failure(body)
}
c @ 500...599 => {
debug!("Server Error 5xx: {}", c);
debug!("Content-Length Check: {}", check_content_length(&resp));
debug!("Content-Type Check: {}",
check_content_type_problem_json(&resp));
on_failure(body)
}
c @ _ => {
Err(::EdgeGridError {
title: Some(format!("Unknown Error: {}", c)),
detail: Some(body),
..Default::default()
})
}
}
}
pub fn gen_error_output(body: String) -> ::EdgeGridResult {
debug!("{}", body);
let json: ::EdgeGridError = try!(serde_json::from_str(&body));
debug!("{:?}", json);
Err(json)
}
pub fn gen_output<T>(body: String) -> ::EdgeGridResult
where T: fmt::Display + fmt::Debug + Deserialize
{
debug!("{}", body);
let json = try!(serde_json::from_str::<T>(&body));
debug!("{:?}", json);
Ok(format!("{}", json))
}
pub fn check_content_length(resp: &http::Response) -> bool {
let given: usize = match resp.get_header("content-length")[0].parse() {
Ok(g) => g,
Err(_) => return false,
};
given == resp.get_body().len()
}
pub fn check_content_type_json(resp: &http::Response) -> bool {
let ref given: String = resp.get_header("content-type")[0];
given.starts_with("application/json")
}
pub fn check_content_type_problem_json(resp: &http::Response) -> bool {
let ref given: String = resp.get_header("content-type")[0];
given == "application/problem+json"
}