Created
May 12, 2019 19:37
-
-
Save vcapra1/2dc30575f798d9702433a6c57882862b to your computer and use it in GitHub Desktop.
Rocket.rs route by subdomain
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
use rocket::{request::FromRequest, Outcome, Request}; | |
pub struct WWWHost; | |
pub struct AAAHost; | |
impl<'a, 'r> FromRequest<'a, 'r> for WWWHost { | |
type Error = (); | |
fn from_request(request: &'a Request<'r>) -> rocket::request::Outcome<Self, Self::Error> { | |
if let Some(hostname) = request.headers().get_one("host") { | |
if hostname == "example.com" { | |
Outcome::Success(WWWHost) | |
} else if hostname == "www.example.com" { | |
Outcome::Success(WWWHost) | |
} else { | |
Outcome::Forward(()) | |
} | |
} else { | |
// There was no host header (this shouldn't happen) | |
Outcome::Forward(()) | |
} | |
} | |
} | |
impl<'a, 'r> FromRequest<'a, 'r> for AAAHost { | |
type Error = (); | |
fn from_request(request: &'a Request<'r>) -> rocket::request::Outcome<Self, Self::Error> { | |
if let Some(hostname) = request.headers().get_one("host") { | |
if hostname == "aaa.example.com" { | |
Outcome::Success(WWWHost) | |
} else { | |
Outcome::Forward(()) | |
} | |
} else { | |
// There was no host header (this shouldn't happen) | |
Outcome::Forward(()) | |
} | |
} | |
} |
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
#[macro_use] | |
extern crate rocket; | |
mod hosts; | |
#[get("/")] | |
fn root(host: WWWHost) -> String { | |
String::from("Welcome to www.example.com!"); | |
} | |
#[get("/")] | |
fn sub(host: AAAHost) -> String { | |
String::from("Welcome to aaa.example.com!"); | |
} | |
fn main() { | |
rocket::ignite().mount("/", routes![root, sub]).launch(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's my version which uses the
duplicate
crate, the one for creating the structs is needless and adds extra lines, but it allows for only one allow macro. This includes a default struct which can be removed.