Advertisement
Guest User

Untitled

a guest
May 23rd, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.93 KB | None | 0 0
  1. #[derive(Debug)]
  2. enum Method {
  3. Head,
  4. Option,
  5. Get,
  6. Post,
  7. Patch,
  8. Put,
  9. Delete,
  10. }
  11.  
  12. struct Router;
  13.  
  14. impl Router {
  15. pub fn to<H, P>(&self, method: Method, handler: H) -> &Self
  16. where
  17. H: HandlerFactory<P>,
  18. {
  19. println!("handle route {:?}", method);
  20. self
  21. }
  22. }
  23.  
  24. trait HandlerFactory<P> {
  25. fn call(&self, _: P) -> String;
  26. }
  27.  
  28. impl<F> HandlerFactory<()> for F
  29. where
  30. F: Fn() -> String,
  31. {
  32. fn call(&self, _: ()) -> String {
  33. (self)()
  34. }
  35. }
  36.  
  37. impl<F> HandlerFactory<(Token,)> for F
  38. where
  39. F: Fn(Token) -> String,
  40. {
  41. fn call(&self, params: (Token,)) -> String {
  42. (self)(params.0)
  43. }
  44. }
  45.  
  46. struct Token {}
  47.  
  48. fn public_route() -> String {
  49. "hello world".into()
  50. }
  51. fn private_route(token: Token) -> String {
  52. "hello private world".into()
  53. }
  54.  
  55. fn main() {
  56. let router = Router {};
  57. router
  58. .to(Method::Get, public_route)
  59. .to(Method::Post, private_route);
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement