A simplistic function that wraps around the behaviour of an http get-request as defined in `curl`. As the library gets more complete, a more complete and complex approach might be needed.
(user: &str, url: &str, opts: Option<Vec<(&str, &str)>>)
| 17 | /// As the library gets more complete, a more complete and complex |
| 18 | /// approach might be needed. |
| 19 | pub fn get<R: Decodable>(user: &str, url: &str, opts: Option<Vec<(&str, &str)>>) -> Result<(Vec<R>, Response), ClientError> { |
| 20 | // Creating an empty request with header info needed for all requests. |
| 21 | let mut handle = curl_http::handle(); |
| 22 | let mut request = handle.get(url) |
| 23 | .header("User-Agent", user).header("Accept", API_ACCEPT_HEADER); |
| 24 | |
| 25 | // In case extre header options are needed, |
| 26 | // it can be defined and given via the `opts` parameter. |
| 27 | if opts.is_some() { |
| 28 | for (name, val) in opts.unwrap() { |
| 29 | request = request.header(name, val); |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | // Executing the actual request via curl and storing the response. |
| 34 | let response = request.exec().unwrap(); |
| 35 | // Retrieving the status code from the response object. |
| 36 | let status_code = response.get_code(); |
| 37 | |
| 38 | // Decoding the header and body in a controlled fashion, |
| 39 | // throwing an error in case something went wrong internally, |
| 40 | // replacing a panic, or when a response was negative. |
| 41 | if !check_status_code(status_code) { |
| 42 | return RequestError::new(status_code, response.get_body()); |
| 43 | } |
| 44 | let raw_body = match str::from_utf8(response.get_body()) { |
| 45 | Ok(raw_body) => raw_body, |
| 46 | Err(e) => return InternalError::new(&format!("{}", e)), |
| 47 | }; |
| 48 | match json::decode(raw_body) { |
| 49 | Ok(b) => { |
| 50 | let body: Vec<R> = b; |
| 51 | Ok((body, Response::populate(response.get_headers()))) |
| 52 | }, |
| 53 | Err(e) => InternalError::new(&format!("{}", e)), |
| 54 | } |
| 55 | } |
no test coverage detected