ipify_rs/
lib.rs

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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
//! Ipify
//!
//! My implementation of the ipify-cli.org API to get your own public IP address
//!
//! The fastest way to use it is to use the `myip()` wrapper:
//!
//! Example:
//! ```
//! use ipify_rs::myip;
//!
//! println!("My IP is: {}", myip());
//! ```
//!
//! The full API is described below.

use clap::{crate_name, crate_version};

/// IPv4 endpoint, plain text
const ENDPOINT4: &str = "https://api.ipify.org";
/// IPv6 endpoint, plain text
const ENDPOINT6: &str = "https://api64.ipify.org";
/// IPv4 endpoint, JSON
const ENDPOINT4J: &str = "https://api.ipify.org?format=json";
/// IPv6 endpoint, JSON
const ENDPOINT6J: &str = "https://api64.ipify.org?format=json";

/// Minimalistic API
///
/// Example:
/// ```
/// use ipify_rs::myip;
///
/// println!("{}", myip())
/// ```
///
#[inline]
pub fn myip() -> String {
    Ipify::new().call()
}

/// The current set of operations
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Op {
    /// Plain text
    IPv4,
    /// Plain text (default)
    IPv6,
    /// Json output
    IPv4J,
    /// Json output
    IPv6J,
}

/// The main API struct
#[derive(Clone, Debug)]
pub struct Ipify {
    /// Current type of operation
    pub t: Op,
    /// Endpoint, different for every operation
    pub endp: String,
}

/// Impl. default values.
impl Default for Ipify {
    fn default() -> Self {
        Self::new()
    }
}

/// API Implementation
impl Ipify {
    /// Create a new API instance client with the defaults
    ///
    /// Example:
    /// ```
    /// use ipify_rs::*;
    ///
    /// let a = Ipify::new();
    ///
    /// println!("{}", a.call());
    /// ```
    ///
    pub fn new() -> Self {
        Self {
            t: Op::IPv6,
            endp: ENDPOINT6.to_owned(),
        }
    }

    /// Specify the subsequent operation to perform on `call()`
    ///
    /// Examples:
    /// ```
    /// use ipify_rs::{Ipify, Op};
    ///
    /// let mut a = Ipify::new();
    /// a.set(Op::IPv6J);
    ///
    /// println!("{}", a.call());
    /// ```
    ///
    pub fn set(&self, op: Op) -> Self {
        Self {
            t: op,
            endp: match op {
                Op::IPv4 => ENDPOINT4.to_owned(),
                Op::IPv6 => ENDPOINT6.to_owned(),
                Op::IPv4J => ENDPOINT4J.to_owned(),
                Op::IPv6J => ENDPOINT6J.to_owned(),
            },
        }
    }

    /// Actually perform the API call
    ///
    /// Example:
    /// ```
    /// use ipify_rs::Ipify;
    ///
    /// let r = Ipify::new().call();
    ///
    /// println!("my ip = {}", r);
    /// ```
    ///
    pub fn call(self) -> String {
        let c = reqwest::blocking::ClientBuilder::new()
            .user_agent(format!("{}/{}", crate_name!(), crate_version!()))
            .build()
            .unwrap();
        c.get(self.endp).send().unwrap().text().unwrap()
    }

    /// Actually perform the API call (async version)
    ///
    /// Example:
    /// ```
    /// use ipify_rs::Ipify;
    ///
    /// async {
    ///     let r = Ipify::new().call_async().await;
    ///     println!("my ip = {}", r);
    /// }
    /// ```
    ///
    pub async fn call_async(self) -> String {
        let c = reqwest::ClientBuilder::new()
            .user_agent(format!("{}/{}", crate_name!(), crate_version!()))
            .build()
            .unwrap();
        c.get(self.endp)
            .send()
            .await
            .unwrap()
            .text()
            .await
            .unwrap()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use httpmock::prelude::*;
    use std::net::IpAddr;

    #[test]
    fn test_set_1() {
        let c = Ipify::new();

        assert_eq!(Op::IPv6, c.t);
        let c = c.set(Op::IPv4J);
        assert_eq!(Op::IPv4J, c.t);
        let c = c.set(Op::IPv6);
        assert_eq!(Op::IPv6, c.t);
    }

    #[test]
    fn test_set_2() {
        let c = Ipify::new();

        let c = c.set(Op::IPv4J).set(Op::IPv6J);
        assert_eq!(Op::IPv6J, c.t);
    }

    #[test]
    fn test_with_1() {
        let c = Ipify::new();

        assert_eq!(Op::IPv6, c.t);
    }

    #[test]
    fn test_with_set() {
        let c = Ipify::new();

        assert_eq!(Op::IPv6, c.t);
        let c = c.set(Op::IPv4);
        assert_eq!(Op::IPv4, c.t);

        let c = c.set(Op::IPv4J);
        assert_eq!(Op::IPv4J, c.t);
    }

    #[test]
    fn test_myip() {
        let server = MockServer::start();

        let m = server.mock(|when, then| {
            when.method(GET).header(
                "user-agent",
                format!("{}/{}", crate_name!(), crate_version!()),
            );
            then.status(200).body("192.0.2.1");
        });

        let mut c = Ipify::new();
        let b = server.base_url().clone();
        c.endp = b.to_owned();
        let str = c.call();

        let ip = str.parse::<IpAddr>();
        m.assert();
        assert!(ip.is_ok());
        assert_eq!("192.0.2.1", str);
    }

    #[tokio::test]
    async fn test_async_call() {
        async_std::task::block_on(async {
            let server = MockServer::start_async().await;

            let m = server
                .mock_async(|when, then| {
                    when.method(GET).header(
                        "user-agent",
                        format!("{}/{}", crate_name!(), crate_version!()),
                    );
                    then.status(200).body("192.0.2.1");
                })
                .await;

            let mut c = Ipify::new();
            let b = server.base_url().clone();
            c.endp = b.to_owned();
            let str = c.call_async().await;

            let ip = str.parse::<IpAddr>();
            m.assert_async().await;
            assert!(ip.is_ok());
            assert_eq!("192.0.2.1", str);
        });
    }
}