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
use hyper::header::Headers;
use hyper::client;
use std::sync::Arc;
use error::Result;
use std::io::Read;
header! { (XStarfighterAuthorization, "X-Starfighter-Authorization") => [String] }
#[derive(Debug, Clone)]
pub struct AuthHttpClient {
api_key: String,
http_client: Arc<client::Client>,
}
pub trait HttpClient {
fn get(&self, url: &str) -> Result<String>;
fn post(&self, url: &str, body: Option<&str>) -> Result<String>;
fn delete(&self, url: &str) -> Result<String>;
}
impl AuthHttpClient {
pub fn new(key: &str) -> AuthHttpClient {
AuthHttpClient {
api_key: key.to_string(),
http_client: Arc::new(client::Client::new()),
}
}
fn build_post<'a>(&'a self, url: &str, body: Option<&'a str>) -> client::RequestBuilder {
let mut build = self.http_client.post(url);
if let Some(b) = body {
build = build.body(b);
}
build = self.add_header(build);
build
}
fn build_get(&self, url: &str) -> client::RequestBuilder {
let mut build = self.http_client.get(url);
build = self.add_header(build);
build
}
fn build_delete(&self, url: &str) -> client::RequestBuilder {
let mut build = self.http_client.delete(url);
build = self.add_header(build);
build
}
fn add_header<'a>(&'a self, b: client::RequestBuilder<'a>) -> client::RequestBuilder {
let mut headers = Headers::new();
headers.set(XStarfighterAuthorization(self.api_key.clone()));
b.headers(headers)
}
}
impl HttpClient for AuthHttpClient {
fn get(&self, url: &str) -> Result<String> {
let mut r = try!(self.build_get(url).send());
let mut buf = String::new();
try!(r.read_to_string(&mut buf));
trace!("get buf = {:?}", buf);
Ok(buf)
}
fn post(&self, url: &str, body: Option<&str>) -> Result<String> {
let mut r = try!(self.build_post(url, body).send());
let mut buf = String::new();
try!(r.read_to_string(&mut buf));
trace!("post buf = {:?}", buf);
Ok(buf)
}
fn delete(&self, url: &str) -> Result<String> {
let mut r = try!(self.build_delete(url).send());
let mut buf = String::new();
try!(r.read_to_string(&mut buf));
trace!("del buf = {:?}", buf);
Ok(buf)
}
}