Skip to content
This repository was archived by the owner on Jul 19, 2019. It is now read-only.

Add perl6 server example #167

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,13 @@ cpan Mojolicious
perl server.pl
```

### Rakudo aka Perl6

```sh
zef install cro JSON::Fast
perl6 server.p6
```

And visit <http://localhost:3000/>. Try opening multiple tabs!

## Changing the port
Expand Down
45 changes: 45 additions & 0 deletions server.p6
Original file line number Diff line number Diff line change
@@ -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<index.html>;
}
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<PORT> || 3000;
my Cro::Service $hello = Cro::HTTP::Server.new:
:host<localhost>, :$port, :$application;
$hello.start;
react whenever signal(SIGINT) { $hello.stop; exit; }