Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to use perl as my web server for a specific address:port number, 10.x.x.x:portNumber, while also having it show what's in my index.html file by default. However, perl does not show the contents of index.html when I run 10.x.x.x:portNumber in my browser. How can I get perl to read from a file?

This is the code I'm working with for this problem.

#!/usr/bin/perl
{
package MyWebServer;
use HTTP::Server::Simple::CGI;
use base qw(HTTP::Server::Simple::CGI);
my %dispatch = (
    '/' => &resp_hello,
);


sub handle_request {
    my $self = shift;
    my $cgi  = shift;
    my $path = $cgi->path_info();
    my $handler = $dispatch{$path};
    if (ref($handler) eq "CODE") {
        print "HTTP/1.0 200 OK
";
        $handler->($cgi);
    } else {
        print "HTTP/1.0 404 Not found
";
        print $cgi->header,
        $cgi->start_html('Not found'),
        $cgi->h1('Not found'),
        $cgi->end_html;
    }
}


sub resp_hello {
    my $cgi  = shift;   # CGI.pm object
    return if !ref $cgi;
    my $who = $cgi->param('name');   
    print $cgi->header,
        $cgi->start_html("Hello"),
        $cgi->h1("Hello Perl"),
        $cgi->end_html;
}
}


my $pid = MyWebServer->new(XXXX)->background();
print "Use 'kill $pid' to stop server.
";

Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
188 views
Welcome To Ask or Share your Answers For Others

1 Answer

Your code is explicitly configured run resp_hello() when you access your server's root URL.

my %dispatch = (
    '/' => &resp_hello,
);

I don't know exactly what URL structure you are hoping to implement, but if you're trying to differentiate / and /index.html then you could do something like this:

my %dispatch = (
    '/' => &resp_hello,
    '/index.html' => &resp_index,
);

and then write a resp_index() subroutine which opens the index.html file and returns the contents to the browser.

You could extend this I suppose and serve any files that exist on the filesystem directly.

But I have to wonder why you're doing this all yourself and not just reaching for a solution that uses PSGI and Plack. Where did you get the idea to use HTTP::Server::Simple?

And I'm appalled to see documentation that encourages the use of the HTML-generation functions from CGI.pm. We've all known what a terrible idea they are for some considerable time, and they are now deprecated.

Before you spend too long going down this path, I'd urge you to investigate more standard Perl web tools.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...