-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathcounter.psgi
executable file
·106 lines (81 loc) · 2.3 KB
/
counter.psgi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#!/usr/bin/perl
use strict;
use warnings;
use 5.010;
use Dancer;
use DBI;
use File::Spec;
use FindBin;
use Imager;
use Imager::File::PNG;
use URI;
my $dbh = init_db_connection();
get '/' => sub {
my $count = increment_and_get_count($dbh);
return count_to_image($count);
};
dance;
#######################################
sub init_db_connection {
# connect to the SQLite database
my $counter_db_file = File::Spec->catfile($FindBin::Bin, 'counter.db');
my $dbh = DBI->connect(
"dbi:SQLite:dbname=${counter_db_file}", # data source
"", # username
"", # password
{ RaiseError => 1 }, # throw exceptions on failure
) or die "Failed to connect to SQLite DB: $DBI::errstr";
# maybe initialize
maybe_initialize_db($dbh);
return $dbh;
}
sub maybe_initialize_db {
my $dbh = shift;
$dbh->do("CREATE TABLE IF NOT EXISTS Count(count INT DEFAULT 0);");
my $sth = $dbh->prepare("SELECT count FROM Count;");
$sth->execute();
if (!$sth->fetchrow()) {
$dbh->do("INSERT INTO Count VALUES(0)");
}
return;
}
sub increment_and_get_count {
my $dbh = shift;
$dbh->do("UPDATE Count SET count = count + 1;");
my $sth = $dbh->prepare("SELECT count FROM Count;");
$sth->execute();
my ($count) = $sth->fetchrow();
return $count;
}
sub count_to_image {
my $count = shift;
my $width = 20 * length($count);
my $image = Imager->new(
xsize => $width,
ysize => 30,
channels => 4
);
$image->box(filled => 1, color => '#FFFFFF');
my $font_file = File::Spec->catfile($FindBin::Bin, 'Ubuntu-L.ttf');
my $font = Imager::Font->new(
file => $font_file,
color => '#000000',
size => 30
);
$image->align_string(
string => "$count",
font => $font,
x => 5,
y => 15,
halign => 'left',
valign => 'center',
aa => 1, # anti-aliasing
) or die $image->errstr;
my $image_data;
$image->write(type => 'png', data => \$image_data)
or die $image->errstr;
my $URI = URI->new("data:");
$URI->media_type("image/png");
$URI->data("$image_data");
return "<img src='$URI' alt='Counter: $count'>";
}