Bailamos

Since spanish classes (I mean the classes at the University, not the type definitions, you wierdo) aren’t as exciting as I would like them to be, my thoughts have wondered a bit further. Yeah, Perl 6 again. The idea isn’t new, but the point of showing off the intersting things it always fresh. So, ladies and gents, here’s a minimal part of Dancer implemented in Perl 6! To give some justice to my spanish classes, it’s not named Dancer, or even MiniDancer.


module Bailador;

use HTTP::Server::Simple::PSGI;

my @routes;

multi get(Pair $x) is export {
    @routes.push: $x;
}

sub dispatch($env) {
    for @routes -> $r {
        if $env ~~ $r.key {
            if $/ {
                return $r.value.(|$/.list);
            } else {
                return $r.value.();
            }
        }
    }
    return "404";
}

sub bailar is export {
    my $app = sub ($env) {
        my $res = dispatch($env);
        return ['200', [ 'Content-Type' => 'text/plain' ], $res];
    }

    given HTTP::Server::Simple::PSGI.new {
        .host = 'localhost';
        .app($app);
        .run;
    }
}

Although simple and stupid, it works. Let’s see some example application:

use Bailador;

# simple cases
get '/' => sub {
    "hello world"
};

get '/about' => sub {
    "about me"
};

# regexes, as usual
get /foo(.+)/ => sub ($x) {
    "regexes! I got $x"
}

get / '/' (.+) '-' (.+)/ => sub ($x, $y) {
    "$x and $y"
}

# junctions work too
get any('/h', '/help', '/halp') => sub {
    "junctions are cool"
}

bailar;

The glory of smartmatching gives as the ability to use the get() sub with regexes and junctions (and almost everything else in Perl 6 to be honest) without even thinking about it.

Now where’s named parameters, where are the other HTTP methods? Well, that is left as an excercise for the reader. I hope you’re inspired enough :)

Advertisements

2 Comments on “Bailamos”

  1. Lee says:

    Very succinct! I have implemented similar dispatchers in Perl 5, but it looks much cleaner using some of the newer Perl 6 features.

    I am curious what the pipe in ‘$r.value.(|$/.list);’ does.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s