From 271d2861b560d71edbf2be1ccd557d12f3afe9d3 Mon Sep 17 00:00:00 2001 From: cono Date: Wed, 6 Jun 2018 02:22:19 +0300 Subject: [PATCH] Add perl6 server example --- README.md | 7 +++++++ server.p6 | 45 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 server.p6 diff --git a/README.md b/README.md index 4862f5df..6c6a93ce 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,13 @@ cpan Mojolicious perl server.pl ``` +### Rakudo aka Perl6 + +```sh +zef install cro JSON::Fast +perl6 server.p6 +``` + And visit . Try opening multiple tabs! ## Changing the port diff --git a/server.p6 b/server.p6 new file mode 100644 index 00000000..212fc052 --- /dev/null +++ b/server.p6 @@ -0,0 +1,45 @@ +# This file provided by Facebook is for non-commercial testing and evaluation +# purposes only. Facebook reserves all rights not expressly granted. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +# FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +use v6; + +use Cro::HTTP::Server; +use Cro::HTTP::Router; +use JSON::Fast; + +my $comments-file = 'comments.json'; + +my $application = route { + get -> *@path { + static 'public', @path, :indexes; + } + get -> 'api', 'comments' { + cache-control :no-cache; + static $comments-file; + response.append-header('Access-Control-Allow-Origin', '*'); + } + post -> 'api', 'comments' { + request-body -> (:$id, :$author, :$text) { + my $comments = from-json $comments-file.IO.slurp; + $id ||= (now * 10 ** 7).Int; + $comments.push: { :$id, :$author, :$text }; + $comments-file.IO.open(:w).print(to-json $comments); + cache-control :no-cache; + response.append-header('Access-Control-Allow-Origin', '*'); + content 'application/json', $comments; + } + } +} + +my $port = %*ENV || 3000; +my Cro::Service $hello = Cro::HTTP::Server.new: + :host, :$port, :$application; +$hello.start; +react whenever signal(SIGINT) { $hello.stop; exit; }