]>
Commit | Line | Data |
---|---|---|
597641fd DM |
1 | use failure::*; |
2 | ||
3 | use http::Uri; | |
4 | use hyper::Body; | |
5 | use hyper::client::Client; | |
6 | use hyper::rt::{self, Future}; | |
7 | ||
8 | pub struct HttpClient { | |
9 | server: String, | |
10 | } | |
11 | ||
12 | impl HttpClient { | |
13 | ||
14 | pub fn new(server: &str) -> Self { | |
15 | Self { | |
16 | server: String::from(server), | |
17 | } | |
18 | } | |
19 | ||
20 | pub fn upload(&self, body: Body, path: &str) -> Result<(), Error> { | |
21 | ||
22 | let client = Client::new(); | |
23 | ||
24 | let url: Uri = format!("http://{}:8007/{}", self.server, path).parse()?; | |
25 | ||
26 | use http::Request; | |
27 | use futures::stream::Stream; | |
28 | ||
29 | let request = Request::builder() | |
30 | .method("POST") | |
31 | .uri(url) | |
32 | .header("User-Agent", "proxmox-backup-client/1.0") | |
33 | .body(body)?; | |
34 | ||
35 | let future = client | |
36 | .request(request) | |
37 | .map_err(|e| Error::from(e)) | |
38 | .and_then(|resp| { | |
39 | ||
40 | let status = resp.status(); | |
41 | ||
42 | resp.into_body().concat2().map_err(|e| Error::from(e)) | |
43 | .and_then(move |data| { | |
44 | ||
45 | let text = String::from_utf8(data.to_vec()).unwrap(); | |
46 | if status.is_success() { | |
47 | println!("Result {} {}", status, text); | |
48 | } else { | |
49 | eprintln!("HTTP Error {}: {}", status, text); | |
50 | } | |
51 | Ok(()) | |
52 | }) | |
53 | }) | |
54 | .map_err(|err| { | |
55 | eprintln!("Error: {}", err); | |
56 | }); | |
57 | ||
58 | // drop client, else client keeps connectioon open (keep-alive feature) | |
59 | drop(client); | |
60 | ||
61 | rt::run(future); | |
62 | ||
63 | Ok(()) | |
64 | } | |
65 | } |