Web Service One-Liners with Dancer

Posted in: Technical Track

Today, I had a bit of fun and created a micro-web service as a one-liner. Something like:

$ perl -MDancer -e'get"/",sub { "current time: " . localtime }; dance' 

But then I thought that using almost 70 characters for a web service was awfully long-winded. Surely there was a way to make our Dancer more efficient. But how? How about getting an MC involved?

package C;

use Dancer;

{ package ::main; use Dancer ':syntax'; }

END {
    get '/' => \&::index if defined &::index;
    dance;
}

1;

With that little module, I can now do:

# in one console

$ perl -Ifiles -MC -e'sub index { "the time is " . localtime }'
>> Dancer 1.3095 server 5780 listening on http://0.0.0.0:3000
== Entering the development dance floor ...

# and in the next

$ curl localhost:3000
the time is Mon Sep 10 22:22:00 2012

Or try for a tad more sophisticated:

# in the first console

$ perl -Ifiles -MC
my $secret;

get '/' => sub { $secret };

put '/*' => sub { ( $secret ) = splat };
^D

>> Dancer 1.3095 server 5961 listening on http://0.0.0.0:3000
== Entering the development dance floor ...

# and in the second

$ curl -X PUT http://localhost:3000/abracadabra
1

$ curl http://localhost:3000
abracadabra

So, yeah, I’m back. Missed me? :-)

email

Interested in working with Yanick? Schedule a tech call.

No comments

Leave a Reply

Your email address will not be published. Required fields are marked *