How to route a request differently with iron/router based on the user agent?

149 Views Asked by At

I would like my Rust application to serve different content to clients depending on the user agent they provide. (I want to return plaintext for cURL clients and HTML for everything else.)

I am using iron/router and I have index.html in the static directory:

let mut mount = Mount::new();
mount.mount("/", Static::new(Path::new("static")));

How would I go about keeping the existing behavior (serving the HTML file) when a web browser requests the page, but serving a plaintext string (generated by a function) when the user agent belongs to cURL?

1

There are 1 best solutions below

0
Luca P. On

The HTTP package you mention appears to a moved slightly. Anyway, many Rust developers will access the request in a webserver framework like Hyper (popular choice). In that case, you can get the User-Agent header with:

let ua = _req.headers().get("User-Agent");
// variable here is not a string, it's an Option<&HeaderValue>
// You'll need to check that it contains a value before you proceed
// to unwrap it. For ex:

if ua.is_some() {
    println!("{}", ua.unwrap().to_str().unwrap())

Please note that analyzing the UserAgent string is pretty rudimentary and it might not be future proof. If you want to check a client (device) property/capability, you may want to check out something like the WURFL API for Rust (not an Open Source product). WURFL will map the user-agent string and other HTTP headers to a profile of the device/browser. To give you an example, let's say that you want to handle tablets differently from other clients:

let device_res = engine.lookup_useragent(ua);
let d = match device_res {
    Ok(d) => {
        println!("Detected Device ID: {}", d.get_device_id());
        d
    }
    Err(_) => panic!("Lookup user agent failed")
};
let is_tablet = d.get_capability("is_tablet");
if is_tablet.unwrap() == "true" {
    // do something for tablets
    println!("TABLET")
}
else {
    // do something else for devices that are not tablets
    println!(" NOT A TABLET")

(more info about WURFL for Rust here).