How to return a json in a mini web server without any additional module?

294 Views Asked by At

So my problem is that i have a perl5.8 installation and i can't install any additional module. (I am a public servant and i have to use the servers as they are without any right on it or choosing what i can install on it, the process to modify something take years).

So there is a little web server script :

use HTTP::Daemon;
use HTTP::Status;

(my $d = new HTTP::Daemon 
LocalAddr => '127.0.0.1',
LocalPort => 52443
) || die;
print "Please contact me at: <URL:", $d->url, ">\n";
while (my $c = $d->accept) {
    while (my $r = $c->get_request) {
        if ($r->method eq 'GET' and $r->uri->path eq "/xyzzy") {
            # remember, this is *not* recommended practice :-)
            $c->send_file_response("D:/Script/index.html");
        }
        else {
            $c->send_error(RC_FORBIDDEN)
        }
    }
    $c->close;
    undef($c);
}

And i would like to return a json like : {"Status" : "Ok" }

regards

1

There are 1 best solutions below

8
Dave Cross On

Rewriting the example in the documentation to return JSON would look something like this:

#!/usr/bin/perl

use strict;
use warnings;

use HTTP::Daemon;
use HTTP::Status;
use HTTP::Response;
use HTTP::Headers;
use JSON::PP;

my $headers = HTTP::Headers->new;
$headers->header(Content_Type => 'application/json');
my $content = JSON::PP->new->utf8->encode({ Status => 'Ok' });

my $d = HTTP::Daemon->new || die;
print "Please contact me at: <URL:", $d->url, ">\n";
while (my $c = $d->accept) {
    while (my $r = $c->get_request) {
        if ($r->method eq 'GET' and $r->uri->path eq "/xyzzy") {
            $c->send_response(
                HTTP::Response->new(200, 'OK', $headers, $content)
            );
        }
        else {
            $c->send_error(RC_FORBIDDEN)
        }
    }
    $c->close;
    undef($c);
}

But please note that writing a web application at this level is rarely a useful thing to do. You really want to install a web framework (I like Dancer2) as that will make your life far easier.

I'm not sure what is imposing these restrictions on you. But if you're not using a modern version of Perl (5.10 at the very least) and installing modules from CPAN, then you're making your Perl development career far harder than it needs to be.