mirror of
https://github.com/icewind1991/warp-real-ip.git
synced 2026-06-03 18:54:06 +02:00
Refactor.
This commit is contained in:
parent
c6af4e7ae9
commit
6825c6da12
2 changed files with 12 additions and 3 deletions
11
src/lib.rs
11
src/lib.rs
|
|
@ -7,16 +7,19 @@ use std::str::FromStr;
|
||||||
use warp::filters::addr::remote;
|
use warp::filters::addr::remote;
|
||||||
use warp::Filter;
|
use warp::Filter;
|
||||||
|
|
||||||
#[derive(Clone)]
|
/// Represents a set of IP networks.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
pub struct IpNetworks {
|
pub struct IpNetworks {
|
||||||
networks: Vec<IpNetwork>,
|
networks: Vec<IpNetwork>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl IpNetworks {
|
impl IpNetworks {
|
||||||
|
/// Checks if addr is part of any IP networks included.
|
||||||
pub fn contains(&self, addr: &IpAddr) -> bool {
|
pub fn contains(&self, addr: &IpAddr) -> bool {
|
||||||
self.networks.iter().any(|&network| network.contains(*addr))
|
self.networks.iter().any(|&network| network.contains(*addr))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Special constructor that builds IpNetwork from an iterator of IP addresses.
|
||||||
pub fn from_ipaddr_iter<'a, T: Iterator<Item = &'a IpAddr>>(addrs: T) -> Self {
|
pub fn from_ipaddr_iter<'a, T: Iterator<Item = &'a IpAddr>>(addrs: T) -> Self {
|
||||||
Self::from_iter(addrs.map(|&addr| -> IpNetwork {
|
Self::from_iter(addrs.map(|&addr| -> IpNetwork {
|
||||||
match addr {
|
match addr {
|
||||||
|
|
@ -27,6 +30,12 @@ impl IpNetworks {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl From<&Vec<IpAddr>> for IpNetworks {
|
||||||
|
fn from(addrs: &Vec<IpAddr>) -> Self {
|
||||||
|
Self::from_ipaddr_iter(addrs.iter())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl FromIterator<IpNetwork> for IpNetworks {
|
impl FromIterator<IpNetwork> for IpNetworks {
|
||||||
fn from_iter<T: IntoIterator<Item = IpNetwork>>(addrs: T) -> Self {
|
fn from_iter<T: IntoIterator<Item = IpNetwork>>(addrs: T) -> Self {
|
||||||
IpNetworks {
|
IpNetworks {
|
||||||
|
|
|
||||||
|
|
@ -1,10 +1,10 @@
|
||||||
use std::net::IpAddr;
|
use std::net::IpAddr;
|
||||||
use warp::Filter;
|
use warp::Filter;
|
||||||
use warp_real_ip::{IpNetworks, real_ip};
|
use warp_real_ip::real_ip;
|
||||||
|
|
||||||
fn serve<'a>(trusted: Vec<IpAddr>) -> impl Filter<Extract = (String,)> + 'a {
|
fn serve<'a>(trusted: Vec<IpAddr>) -> impl Filter<Extract = (String,)> + 'a {
|
||||||
warp::any()
|
warp::any()
|
||||||
.and(real_ip(IpNetworks::from_ipaddr_iter(trusted.iter())))
|
.and(real_ip((&trusted).into()))
|
||||||
.map(|addr: Option<IpAddr>| addr.unwrap().to_string())
|
.map(|addr: Option<IpAddr>| addr.unwrap().to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue