From e756ca6d6e4219b6fbe2d7a72fc3d32a69d72f06 Mon Sep 17 00:00:00 2001 From: swaggboi Date: Sat, 6 Mar 2021 17:20:56 -0500 Subject: [PATCH] Implement visitor counter --- .gitignore | 2 ++ templates/index.html.ep | 2 +- www-swagg.pl | 24 +++++++++++++++++++++++- 3 files changed, 26 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index 8b697d3..7c92da7 100644 --- a/.gitignore +++ b/.gitignore @@ -35,3 +35,5 @@ inc/ /pm_to_blib /*.zip +# Visitor counter +/.counts diff --git a/templates/index.html.ep b/templates/index.html.ep index d8a3d09..ae436d6 100644 --- a/templates/index.html.ep +++ b/templates/index.html.ep @@ -91,7 +91,7 @@ +--------------------------+
-

TODO: visitor count goes here

+

You are visitor number <%= $count %>.

+--------------------------+
diff --git a/www-swagg.pl b/www-swagg.pl index 9243501..557a24c 100755 --- a/www-swagg.pl +++ b/www-swagg.pl @@ -6,13 +6,35 @@ use Mojolicious::Lite; use Regexp::Common qw{net}; use Digest::SHA qw{sha1_hex}; +use Fcntl qw{:flock :seek}; +use Number::Format qw{format_number}; # The main landing page; pass in the output of the fortune command get '/' => sub { my ($c) = @_; my $fortune = `fortune` || "huh?? no fortune for u\n"; + my ($count, %serverSide); - $c->render(fortune => $fortune); + # Visitor counter ala the ol' count.cgi script + # TODO: clean up and variable-ize filehandles + open(IN,"+<.counts"); # Open it + flock(IN,LOCK_EX); # Lock the file (exclusive lock) + seek(IN,0,SEEK_SET); # Rewind it to the beginning + $count = ; # Read only the first line + $count = ++$count; # Increment counter + truncate(IN,0); # This erases the file to length=0 + seek(IN,0,SEEK_SET); # Rewind it to the beginning + print IN "$count\n"; # Write out the new count + close(IN); # Close the file. + $count = format_number($count); # Add commas + + # Gather all our server-side stuff + %serverSide = ( + count => $count, + fortune => $fortune + ); + + $c->render(%serverSide); } => 'index'; # Deprecation of IE page