]> git.proxmox.com Git - proxmox-backup.git/blame - src/client/http_client.rs
client/http_client.rs: new helper class
[proxmox-backup.git] / src / client / http_client.rs
CommitLineData
597641fd
DM
1use failure::*;
2
3use http::Uri;
4use hyper::Body;
5use hyper::client::Client;
6use hyper::rt::{self, Future};
7
8pub struct HttpClient {
9 server: String,
10}
11
12impl 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}