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
extern crate reqwest;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate failure;
use std::net::IpAddr;
use failure::Error;
use reqwest::Client;
#[derive(Debug)]
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
#[derive(Clone, PartialEq, Eq)]
pub struct GeoInfo {
pub ip_address: String,
pub country_code: String,
pub country_name: String,
pub region_name: String,
pub city_name: String,
pub zip_code: String,
pub latitude: String,
pub longitude: String,
pub time_zone: String,
}
pub fn query(api_key: &str, ip: Option<IpAddr>) -> Result<GeoInfo, Error> {
let client = Client::new();
let mut request = client.get("http://api.ipinfodb.com/v3/ip-city/");
request.query(&[("key", api_key), ("format", "json")]);
if let Some(addr) = ip {
request.query(&[("ip", addr)]);
}
let geo_info: GeoInfo = request.send()?.json()?;
Ok(geo_info)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
let ipaddr = "8.8.8.8".parse().unwrap();
let queried_geo_info = query("YOUR_API_KEY", Some(ipaddr)).unwrap();
let geo_info = GeoInfo {
ip_address: "8.8.8.8".to_string(),
country_code: "US".to_string(),
country_name: "United States".to_string(),
region_name: "California".to_string(),
city_name: "Mountain View".to_string(),
zip_code: "94043".to_string(),
latitude: "37.406".to_string(),
longitude: "-122.079".to_string(),
time_zone: "-07:00".to_string(),
};
assert_eq!(geo_info, queried_geo_info);
}
}