From 5b66e09ed828036d9f2dc24fe21a0122164a8a7a Mon Sep 17 00:00:00 2001 From: eleksir Date: Wed, 28 Aug 2019 23:27:17 +0300 Subject: [PATCH] Initial commit --- lib/fortune.pm | 12 ++++++++++ lib/ping.pm | 12 ++++++++++ lib/utils.pm | 24 +++++++++++++++++++ myapi.psgi | 63 ++++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 111 insertions(+) create mode 100644 lib/fortune.pm create mode 100644 lib/ping.pm create mode 100644 lib/utils.pm create mode 100644 myapi.psgi diff --git a/lib/fortune.pm b/lib/fortune.pm new file mode 100644 index 0000000..011a349 --- /dev/null +++ b/lib/fortune.pm @@ -0,0 +1,12 @@ +package fortune; + +use strict; +use vars qw/$VERSION/; + +$VERSION = "1.0"; + +sub quote { + return ('200', 'text/plain', `fortune`); +} + +1; diff --git a/lib/ping.pm b/lib/ping.pm new file mode 100644 index 0000000..f674c8c --- /dev/null +++ b/lib/ping.pm @@ -0,0 +1,12 @@ +package ping; + +use strict; +use vars qw/$VERSION/; + +$VERSION = "1.0"; + +sub pong { + return ('200', 'text/plain', "pong\n"); +} + +1; diff --git a/lib/utils.pm b/lib/utils.pm new file mode 100644 index 0000000..1faa3a8 --- /dev/null +++ b/lib/utils.pm @@ -0,0 +1,24 @@ +package utils; + +use strict; +use vars qw/$VERSION/; + +$VERSION = "1.0"; + +sub ip ($) { + my $env = shift; + my $msg = ''; + + if (defined($env->{X_REAL_IP})) { + $msg = $env->{X_REAL_IP}; + } elsif (defined($env->{X_FORWARDED_FOR})) { + $msg = (split(/\,/, $env->{X_FORWARDED_FOR}, 2))[0]; + } else { + $msg = $env->{REMOTE_ADDR}; + } + + $msg .= "\n"; + return ('200', 'text/plain', $msg); +} + +1; diff --git a/myapi.psgi b/myapi.psgi new file mode 100644 index 0000000..851cba6 --- /dev/null +++ b/myapi.psgi @@ -0,0 +1,63 @@ +use Data::Dumper; +use strict; +use warnings "all"; +use JSON::PP; +use threads; +use threads::shared; + +# my plugins +use lib "$ENV{'HOME'}/.local/var/www/psgi/lib"; +use ping; +use utils; +use fortune; + +sub mythread(); + +my $main :shared = 0; + +#unless ($main) { threads->create('mythread'); } + + +my $app = sub { + my $env = shift; + + my $msg = "Your Opinion is very important for us, please stand by.\n"; + my $status = '404'; + my $content = 'text/plain'; + + if ($env->{PATH_INFO} eq '/d') { + $status = '200'; + $msg = Dumper($env); + } elsif ($env->{PATH_INFO} eq '/ping') { + ($status, $content, $msg) = ping::pong(); + } elsif ($env->{PATH_INFO} eq '/ip') { + ($status, $content, $msg) = utils::ip($env); + } elsif (($env->{PATH_INFO} eq '/fortune') or ($env->{PATH_INFO} eq '/quote')) { + ($status, $content, $msg) = fortune::quote(); + } + + return [ + $status, + [ 'Content-Type' => $content, 'Content-Length' => length($msg) ], + [ $msg ], + ]; +}; + +sub mythread () { + $main = 1; + threads->detach(); + + while (1) { + sleep 1; + open (F, ">>", '/tmp/myapi.txt'); + print F time() . "\n"; + close F; + } +} + +# vim: set ft=perl noet ai : +__END__ + +https://toster.ru/q/75226 + +http://www.cbr.ru/scripts/XML_daily.asp