Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created May 13, 2019 08:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rust-play/7610290a37934703a4450888afb54f2f to your computer and use it in GitHub Desktop.
Save rust-play/7610290a37934703a4450888afb54f2f to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
#[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)
// }
//}
//
//impl<F, P, P2> HandlerFactory<(P, P2)> for F
// where F: Fn(P, P2) -> String,
// P: FromRequest,
// P2: FromRequest
//{
// fn call(&self, params: (P, P2)) -> String {
// (self)(params.0, params.1)
// }
//}
/// FromRequest trait impl for tuples
macro_rules! factory_tuple ({ $(($n:tt, $T:ident)),+} => {
impl<F, $($T,)+> HandlerFactory<($($T,)+)> for F
where F: Fn($($T,)+) -> String,
{
fn call(&self, param: ($($T,)+)) -> String {
(self)($(param.$n,)+)
}
}
});
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 private_route_2(token: Token, path_id: String) -> String {
"hello private world with path".into()
}
factory_tuple!((0, A));
factory_tuple!((0, A), (1, B));
factory_tuple!((0, A), (1, B), (2, C));
fn main() {
let router = Router {};
router
.to(Method::Get, public_route)
.to(Method::Post, private_route)
.to(Method::Get, private_route_with_string)
.to(Method::Get, private_route_2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment