Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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)
}
}
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
You can’t perform that action at this time.