Web Service One-Liners with Dancer

Sep 11, 2012 / By Yanick Champoux

Tags: ,

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? :-)

Leave a Reply

  • (will not be published)

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>