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:

[bash]$ perl -MDancer -e’get"/",sub { "current time: " . localtime }; dance’ [/bash]

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?

[perl]package C;

use Dancer;

{ package ::main; use Dancer ‘:syntax’; }

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

1;
[/perl]

With that little module, I can now do:

[bash]# in one console

$ perl -Ifiles -MC -e’sub index { "the time is " . localtime }’
>> Dancer 1.3095 server 5780 listening on https://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
[/bash]

Or try for a tad more sophisticated:

[bash]# in the first console

$ perl -Ifiles -MC
my $secret;

get ‘/’ => sub { $secret };

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

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

# and in the second

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

$ curl https://localhost:3000
abracadabra
[/bash]

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

email
Want to talk with an expert? Schedule a call with our team to get the conversation started.

No comments

Leave a Reply

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