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
// Copyright 2020 Cognite AS
//! The HTTP Layer
use std::default::Default;

use http_types::headers;

pub struct HTTP<C: http_client::HttpClient> {
    authorization_header: headers::HeaderName,
    app_name_header: headers::HeaderName,
    instance_id_header: headers::HeaderName,
    app_name: String,
    instance_id: String,
    authorization: Option<String>,
    client: surf::Client<C>,
}

impl<C: http_client::HttpClient + std::default::Default> HTTP<C> {
    /// The error type on this will change in future.
    pub fn new(
        app_name: String,
        instance_id: String,
        authorization: Option<String>,
    ) -> Result<Self, http_types::Error> {
        Ok(HTTP {
            client: surf::Client::with_client(Default::default()),
            app_name,
            instance_id,
            authorization,
            authorization_header: headers::HeaderName::from_bytes("authorization".into())?,
            app_name_header: headers::HeaderName::from_bytes("appname".into())?,
            instance_id_header: headers::HeaderName::from_bytes("instance_id".into())?,
        })
    }

    /// Perform a GET. Returns errors per surf::Client::get.
    pub fn get(&self, uri: impl AsRef<str>) -> surf::Request<C> {
        let request = self
            .client
            .get(uri)
            .set_header(self.app_name_header.clone(), self.app_name.as_str())
            .set_header(self.instance_id_header.clone(), self.instance_id.as_str());
        if let Some(auth) = &self.authorization {
            request.set_header(self.authorization_header.clone(), auth.as_str())
        } else {
            request
        }
    }

    /// Perform a GET. Returns errors per surf::Client::get.
    pub fn post(&self, uri: impl AsRef<str>) -> surf::Request<C> {
        let request = self
            .client
            .post(uri)
            .set_header(self.app_name_header.clone(), self.app_name.as_str())
            .set_header(self.instance_id_header.clone(), self.instance_id.as_str());
        if let Some(auth) = &self.authorization {
            request.set_header(self.authorization_header.clone(), auth.as_str())
        } else {
            request
        }
    }
}