Skip to content

Instantly share code, notes, and snippets.

@memememomo
Created February 25, 2014 12:45
Show Gist options
  • Save memememomo/9208139 to your computer and use it in GitHub Desktop.
Save memememomo/9208139 to your computer and use it in GitHub Desktop.
Mojo::Server::Daemonで簡易なWebサーバを作る ref: http://qiita.com/memememomo/items/bafa7929af0ae8ab091c
use strict;
use warnings;
use utf8;
use Encode;
use Mojo::Server::Daemon;
use Test::More;
use Test::TCP;
use Mojo::UserAgent;
test_tcp(
client => sub {
my $post = shift;
my $url = 'http://localhost:'.$post;
my $client = Mojo::UserAgent->new;
my $tx = $client->get($url.'/test.html');
if (my $res = $tx->success) {
is decode_utf8($res->body), '<html><head><title>テスト</title></head><body><h1>テスト</h1></body></html>';
}
$tx = $client->get($url.'/test.txt');
if (my $res = $tx->success) {
is decode_utf8($res->body), 'テスト';
}
},
server => sub {
my $port = shift;
my $daemon = build_server($port);
$daemon->run;
},
);
sub build_server {
my ($port) = @_;
my $daemon = Mojo::Server::Daemon->new(listen => ['http://*:'.$port]);
$daemon->unsubscribe('request');
$daemon->on(request => sub {
my ($daemon, $tx) = @_;
# Request
my $method = $tx->req->method;
my $path = $tx->req->url->path;
if ($path eq '/test.html') {
$tx->res->code(200);
$tx->res->headers->content_type('text/html');
$tx->res->body(encode_utf8('<html><head><title>テスト</title></head><body><h1>テスト</h1></body></html>'));
}
elsif ($path eq '/test.txt') {
$tx->res->code(200);
$tx->res->headers->content_type('text/plain');
$tx->res->body(encode_utf8('テスト'));
}
else {
$tx->res->code(404);
$tx->res->body('Not Found');
}
# Resume transaction
$tx->resume
});
$daemon;
}
done_testing;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment