Hacking Thy Fearful Symmetry

Hacker, hacker coding bright
Powered by a Gamboling Beluga

Web Service one-liners with Dancer

created: September 10, 2012, last updated: September 11, 2012

Today, I had some 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... by getting a 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? :-)

comments powered by Disqus