Created
November 25, 2010 13:08
-
-
Save emasaka/715362 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env perl | |
| use strict; | |
| use warnings; | |
| use HTTP::Daemon; | |
| use Getopt::Long; | |
| use Linux::Inotify2; | |
| use File::Slurp; | |
| my $DEFAULT_PORT = 4000; | |
| my $POLLING_PATH = '/polling'; | |
| sub js { | |
| my $port = shift; | |
| my $polling_path = shift; | |
| sprintf(<<'__JS__', $port, $polling_path); | |
| <script type="text/javascript"> | |
| (function(){ | |
| var mylocation = location; | |
| var xhr = new XMLHttpRequest; | |
| xhr.open("GET", "http://localhost:%d%s", true); | |
| xhr.onload = function(){ mylocation.reload(true); }; | |
| xhr.send(); | |
| })(); | |
| </script> | |
| __JS__ | |
| } | |
| sub make_html { | |
| use Text::Xatena; | |
| my $file = shift; | |
| my $content = read_file($file); | |
| Text::Xatena->new->format($content); | |
| } | |
| sub wait_for_file { | |
| my $file = shift; | |
| my $inotify = Linux::Inotify2->new or die; | |
| $inotify->watch($file, IN_ALL_EVENTS, sub { | |
| my $e = shift; | |
| $e->w->cancel; | |
| }); | |
| 1 while $inotify->poll; | |
| } | |
| GetOptions('css=s' => \(my $css), | |
| 'port=i' => \(my $port)); | |
| my $source = $ARGV[0]; | |
| die unless -r $source; | |
| $port ||= $DEFAULT_PORT; | |
| my $d = HTTP::Daemon->new(LocalAddr => 'localhost', LocalPort => $port) or die; | |
| system 'xdg-open', "http://localhost:${port}/"; | |
| while (my $c = $d->accept) { | |
| while (my $req = $c->get_request) { | |
| my $body; | |
| if ($req->method eq 'GET' && $req->uri->path eq $POLLING_PATH) { | |
| wait_for_file($source); | |
| $body = ''; | |
| } else { | |
| $body = '<html><hread><meta http-equiv="Content-Type" content="text/html; charset=utf-8">'; | |
| $body .= qq(<link rel="stylesheet" type="text/css" href="${css}" />) if $css; | |
| $body .= '</head><body>' . make_html($source) . js($port, $POLLING_PATH) . '</body></html>'; | |
| } | |
| my $res = HTTP::Response->new(200, 'OK', | |
| [{'Content-Type' => 'text/html'}], $body); | |
| $c->send_response($res); | |
| } | |
| $c->close; | |
| undef $c; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment