~rjpcasalino/bss

ref: 3986312629087f22b0b4c99c5cc1306919ec792e bss/lib/webserver.pl -rwxr-xr-x 2.1 KiB
39863126rjpcasalino updates a say 1 year, 4 months ago
                                                                                
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
107
108
109
110
111
112
113
114
#!/usr/bin/env perl

use strict;
use warnings; 

use HTTP::Server::Simple::CGI;

{ package WebServer; use base 'HTTP::Server::Simple::CGI';

use File::Slurp; # import read_file

my $nl = "\x0d\x0a";

my $root = '.';
if (@ARGV) {
  $root = shift;
}
chdir($root);

sub print_header { # {{{

    my $content_type = shift;

    print "HTTP/1.0 200 OK$nl";
    print "Content-Type: $content_type; charset=utf-8$nl$nl";

} # }}}


sub print_400 {
    my $content_type = shift;

    print "HTTP/1.0 400 BAD REQUEST$nl";
    print "Content-Type: $content_type; charset=utf-8$nl$nl";

}

sub serve_file { # {{{

    my $path_relative = shift;
    my $content_type  = shift;

    print_header($content_type);

    print STDOUT "serve_file: $path_relative\n";

    if (-e $path_relative) {
       print read_file($path_relative, binmode => ":raw");
    } else {
       print "file $path_relative not found"; 
    }


} # }}}

sub handle_request {

    my $self = shift;
    my $cgi  = shift;

    my $path = $cgi -> path_info;

    if ($path eq '/') {
      if (-e 'index.html') {
        serve_file ("index.html", 'text/html');
      }
      else {
	print join "\n", glob('*');
      }
      return;
    }

  #  See http://de.selfhtml.org/diverses/mimetypen.htm for Mime Types.

    if ($path =~ /\.htm$/  or $path =~ /\.html$/) {
      serve_file (".$path", 'text/html');
      return;
    }
    if ($path =~ /\.js$/ ) {
      serve_file (".$path", 'application/javascript');
      return;
    }
    if ($path =~ /\.txt$/) {
      serve_file (".$path", 'text/plain');
      return;
    }
    if ($path =~ /\.js$/ ) {
      serve_file (".$path", 'application/javascript');
      return;
    }
    if ($path =~ /\.png$/) {
      serve_file (".$path", 'image/png');
      return;
    }
    if ($path =~ /\.jpg$/ or $path =~ /\.jpeg/) {
      serve_file (".$path", 'image/jpeg');
      return;
    }
    if ($path =~ /\.ico$/) {
      serve_file (".$path", 'image/x-icon');
      return;
    }

    print STDERR "Unknown Mime type for $path\n";
    print_400("text/html");
    return;
}


}

# Use Port 8080 (http://localhost:8080)
my $pid = WebServer -> new(8080) -> background;
print "pid of webserver=$pid\n";