Created
January 25, 2018 20:14
-
-
Save joergrathlev/db055a8677ee7449c826a5677a90cb6d to your computer and use it in GitHub Desktop.
rust meetup 2018-01-25
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![feature(plugin)] | |
#![plugin(rocket_codegen)] | |
extern crate rocket; | |
extern crate ipnetwork; | |
use ipnetwork::{IpNetwork, IpNetworkError}; | |
use rocket::http::RawStr; | |
use rocket::request::FromParam; | |
use std::error::Error; | |
use std::net::IpAddr; | |
use std::str::FromStr; | |
#[get("/<addr>")] | |
fn get_geolocation(addr: IpAddr) -> String { | |
format!("{}", addr) | |
} | |
#[get("/<addr_range>", rank = 2)] | |
fn get_geolocation_from_address_range(addr_range: NetworkRange) -> String { | |
format!("{}", addr_range.0) | |
} | |
struct NetworkRange(IpNetwork); | |
impl FromStr for NetworkRange { | |
type Err = IpNetworkError; | |
fn from_str(s: &str) -> Result<NetworkRange, IpNetworkError> { | |
s.parse().map(NetworkRange) | |
} | |
} | |
impl<'r> FromParam<'r> for NetworkRange { | |
type Error = Box<Error>; | |
fn from_param(param: &'r RawStr) -> Result<Self, Box<Error>> { | |
param.percent_decode() | |
.map_err(|e| Box::new(e) as Box<Error>) | |
.and_then(|decoded_str| decoded_str.parse().map_err(|e| Box::new(e) as Box<Error>)) | |
// match param.percent_decode() { | |
// Ok(decoded_str) => { | |
// match decoded_str.parse() { | |
// Ok(network_range) => Ok(network_range), | |
// Err(e) => Err(Box::new(e)) | |
// } | |
// } | |
// Err(e) => Err(Box::new(e)) | |
// } | |
} | |
} | |
fn main() { | |
rocket::ignite() | |
.mount("/", routes![get_geolocation]) | |
.mount("/", routes![get_geolocation_from_address_range]) | |
.launch(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment