Created
May 13, 2019 08:12
-
-
Save rust-play/4ee6eb1e3dda0f6e7c8858a1c58026ed to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
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
#[derive(Debug)] | |
enum Method { | |
Head, | |
Option, | |
Get, | |
Post, | |
Patch, | |
Put, | |
Delete, | |
} | |
struct Router; | |
impl Router { | |
pub fn to<H, P>(&self, method: Method, handler: H) -> &Self | |
where H: HandlerFactory<P> | |
{ | |
println!("handle route {:?}", method); | |
self | |
} | |
} | |
trait FromRequest { | |
fn from_request() -> Self where Self: Sized; | |
} | |
impl FromRequest for String { | |
fn from_request() -> Self where Self: Sized { | |
"hello world".into() | |
} | |
} | |
struct Token {} | |
impl FromRequest for Token { | |
fn from_request() -> Self where Self: Sized { | |
Self {} | |
} | |
} | |
trait HandlerFactory<P> { | |
fn call(&self, _: P) -> String; | |
} | |
impl<F> HandlerFactory<()> for F where F: Fn() -> String { | |
fn call(&self, _: ()) -> String { | |
(self)() | |
} | |
} | |
impl<F, P> HandlerFactory<(P, )> for F | |
where F: Fn(P) -> String, | |
P: FromRequest | |
{ | |
fn call(&self, params: (P, )) -> String { | |
(self)(params.0) | |
} | |
} | |
fn public_route() -> String { | |
"hello world".into() | |
} | |
fn private_route(token: Token) -> String { | |
"hello private world".into() | |
} | |
fn private_route_with_string(s: String) -> String { | |
"hello private world".into() | |
} | |
fn main() { | |
let router = Router {}; | |
router | |
.to(Method::Get, public_route) | |
.to(Method::Post, private_route) | |
.to(Method::Get, private_route_with_string); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment