Use MaxMindDb and thiserror.
This commit is contained in:
		
							parent
							
								
									c05d9a68f4
								
							
						
					
					
						commit
						83381e4933
					
				
					 3 changed files with 25 additions and 7 deletions
				
			
		
							
								
								
									
										27
									
								
								src/lib.rs
									
										
									
									
									
								
							
							
						
						
									
										27
									
								
								src/lib.rs
									
										
									
									
									
								
							| 
						 | 
				
			
			@ -1,17 +1,32 @@
 | 
			
		|||
use std::net::IpAddr;
 | 
			
		||||
 | 
			
		||||
/// Allows geo-locating IPs and keeps analytics.
 | 
			
		||||
pub struct Locat {}
 | 
			
		||||
pub struct Locat {
 | 
			
		||||
    geoip: maxminddb::Reader<Vec<u8>>,
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
#[derive(Debug, thiserror::Error)]
 | 
			
		||||
pub enum Error {
 | 
			
		||||
    #[error("maxminddb error: {0}")]
 | 
			
		||||
    MaxMindDb(#[from] maxminddb::MaxMindDBError),
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
impl Locat {
 | 
			
		||||
    pub fn new(_geoip_country_db_path: &str, _analytics_db_path: &str) -> Self {
 | 
			
		||||
        // TODO: read geoip db, create analytics db
 | 
			
		||||
        Self {}
 | 
			
		||||
    pub fn new(geoip_country_db_path: &str, _analytics_db_path: &str) -> Result<Self, Error> {
 | 
			
		||||
        // Todo: create analytics db.
 | 
			
		||||
 | 
			
		||||
        Ok(Self {
 | 
			
		||||
            geoip: maxminddb::Reader::open_readfile(geoip_country_db_path)?,
 | 
			
		||||
        })
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    /// Converts an address to an ISO 3166-1 alpha-2 country code.
 | 
			
		||||
    pub fn ip_to_iso_code(&self, _addr: IpAddr) -> Option<&str> {
 | 
			
		||||
        None
 | 
			
		||||
    pub fn ip_to_iso_code(&self, addr: IpAddr) -> Option<&str> {
 | 
			
		||||
        self.geoip
 | 
			
		||||
            .lookup::<maxminddb::geoip2::Country>(addr)
 | 
			
		||||
            .ok()?
 | 
			
		||||
            .country?
 | 
			
		||||
            .iso_code
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    /// Returns a map of country codes to number of requests.
 | 
			
		||||
| 
						 | 
				
			
			
 | 
			
		|||
		Loading…
	
	Add table
		Add a link
		
	
		Reference in a new issue