yapilt/src/lib.rs
2020-04-19 16:31:35 +02:00

84 lines
2.3 KiB
Rust

mod error;
mod provider;
mod ip_type;
pub use error::Error;
pub use provider::Provider;
pub use ip_type::IpType;
pub mod http {
use crate::{Error, IpType, Provider};
use std::default::Default;
pub fn ipv4() -> Result<http::Request<&'static [u8]>, Error> {
ip(IpType::V4, Provider::default())
}
pub fn ipv6() -> Result<http::Request<&'static [u8]>, Error> {
ip(IpType::V6, Provider::default())
}
pub fn ip<T: Into<Provider>>(ip_type: IpType, provider: T) -> Result<http::Request<&'static [u8]>, Error> {
let provider : Provider = provider.into();
provider.ip(ip_type)
}
}
#[cfg(feature = "reqwest-client")]
pub mod reqwest_client {
use reqwest::Client;
use crate::{Error, IpType, Provider, http::ip as http_ip};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::default::Default;
use std::convert::TryInto;
pub async fn ipv4(client: &mut Client) -> Result<Ipv4Addr, Error> {
match ip(client, IpType::V4, Provider::default()).await? {
IpAddr::V4(ip) => Ok(ip),
_ => {
log::error!("This should be unreachable, if the provider is working and configured correctly");
panic!();
}
}
}
pub async fn ipv6(client: &mut Client) -> Result<Ipv6Addr, Error> {
match ip(client, IpType::V6, Provider::default()).await? {
IpAddr::V6(ip) => Ok(ip),
_ => {
log::error!("This should be unreachable, if the provider is working and configured correctly");
panic!();
}
}
}
pub async fn ip<T: Into<Provider>>(client: &mut Client, ip_type: IpType, provider: T) -> Result<IpAddr, Error> {
let request = http_ip(ip_type, provider)?;
let response = client
.execute(request.try_into().unwrap())
.await?
.text()
.await?;
Ok(match ip_type {
IpType::V4 => {
let addr : Ipv4Addr = response.parse().unwrap();
IpAddr::from(addr)
},
IpType::V6 => {
let addr : Ipv6Addr = response.parse().unwrap();
IpAddr::from(addr)
},
})
}
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}