Skip to content

Instantly share code, notes, and snippets.

@tony-o
Created April 12, 2018 22:49
Show Gist options
  • Save tony-o/9991a7932181656ce5d192ece8ac8016 to your computer and use it in GitHub Desktop.
Save tony-o/9991a7932181656ce5d192ece8ac8016 to your computer and use it in GitHub Desktop.

app.pl6

#!/usr/bin/env perl6

use Cro::HTTP::Router;
use lib 'lib';
use Router;

my $application = build-router;

my Cro::Service $hello = Cro::HTTP::Server.new:
    :host<localhost>, :port<10000>, :$application;
$hello.start;
react whenever signal(SIGINT) { $hello.stop; exit; }

routes.yaml

get:
  - Ctrl::Greet::&greet
  - Ctrl::Greet::&bye

lib/Router.pm6

unit module Router;
use Cro::HTTP::Server;
use Cro::HTTP::Router;
use YAML::Parser::LibYAML;

sub build-router is export {
  my %routes = yaml-parse('routes.yaml');
  my %map    = (
    get => &get,
  );
  route {
    for %routes.keys -> $method {
      for @(%routes{$method}) -> $c {
        say "Loading $c";
        try {
          CATCH { default { warn "Failed to load {$c.split('::&')[0]}\n"~$_.Str } };
          my ($ct, $me) = $c.split('::&');
          $me = "&{$me}";
          require ::($ct.Str);
          %map{$method}.( 
            ::("{$ct.Str}::{$me.Str}")
          );
        };
      }
    }
  };
}

lib/Ctrl/Greet.pm6

use Cro::HTTP::Router;
module Ctrl::Greet {

  our sub greet('greet', $word) {
    content 'text/plain', "Hello $word!";
  }

  our sub bye('bye', $word) {
    content 'text/plain', "Good bye $word!";
  }

}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment