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
use reqwest::Url;

/// Library Error type
///
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// Rewqwest HTTP Error
    ///
    #[error("{0}")]
    Reqwest(#[from] reqwest::Error),

    /// Invalid HTTP StatusCode
    ///
    #[error("{0}")]
    InvalidStatus(reqwest::StatusCode),
}

/// An XKCD client
///
#[derive(Debug, Clone)]
pub struct Client {
    client: reqwest::Client,
}

impl Client {
    /// Make a new [`Client`].
    ///
    pub fn new() -> Self {
        Client {
            client: reqwest::Client::new(),
        }
    }

    /// Get a random xkcd comic url.
    ///
    pub async fn get_random(&self) -> Result<Url, Error> {
        let res = self
            .client
            .get("https://c.xkcd.com/random/comic/")
            .send()
            .await?;
        let status = res.status();
        if !status.is_success() {
            return Err(Error::InvalidStatus(status));
        }
        let ret = res.url().clone();
        let _body = res.text().await?;

        Ok(ret)
    }
}

impl Default for Client {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn it_works() {
        let client = Client::new();
        let result = client.get_random().await.expect("failed to get xkcd comic");
        dbg!(result);
    }
}