markdownCache.pl

#!/usr/bin/perl
use strict;
use warnings FATAL => qw(all);

# Demonstrates use of Sloop::Static::Cache to create a dynamically generated
# HTML page from markdown and cache it for subsequent use.

use Sloop::Logger;
use Sloop::Server;
use Sloop::Static::Cache;
use Template;
use Text::Markdown 'markdown';

# Use a global logger.
my $Logger = Sloop::Logger->new();

my $sloop = Sloop::Server->new (
    port => 8080,
    logger => $Logger
);
die if !$sloop;

$sloop->{handlers} = {
    '/' => sub {
    # If you have an entire directory/set of subpaths, use
    # Sloop::Static::Cache::hierarchy instead.
        Sloop::Static::Cache::page (
            shift,
        # Working directory must be writable.
            './markdownCache.html',
        # Use this script as the timestamp source.
            $0,
            \&generatePage
        );
    }
};

$sloop->run;

sub generatePage {
# This will only happen for the first request.
    $Logger->out (
        LOG_REQUEST,
        "Generating HTML page for caching."
    );

    my $template = <<END;
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>[% title %]</title>
<body>
[% body %]
</body>
</html>
END

# Process markdown.
    my $markdown;
    $markdown .= $_ while (<DATA>);
    my $html = markdown($markdown);

# Create a complete HTML page.
    my $tt = Template->new ({
        ANYCASE => 1
    });
    if (!$tt) {
        $Logger->out (
            LOG_ERR,
            'Template->new() fail: '.Template->error()
        );
        return undef;
    }

    my $page;
    if (!$tt->process (
        \$template,
        {
            title => 'Sloop Markdown Demo',
            body => $html
        }, \$page
    )) {
        $Logger->out (
            LOG_ERR,
            'Template::process() fail: '.$tt->error
        );
        return undef;
    }

    return $page;
}


__DATA__
Markdown Example
================

- one
- two
- three

##[Perl Sloop](http://perl-sloop.net)