Annotation of HOPE/Net-OpenAMD/script/test_server.pl, Revision 1.2
1.1 andrew 1: #!/usr/bin/env perl
2:
3: use Mojolicious::Lite;
1.2 ! andrew 4: use Mojo::JSON;
! 5:
! 6: use Data::Dumper;
1.1 andrew 7:
8: use 5.010;
9:
1.2 ! andrew 10: app->renderer->add_helper(
! 11: action => sub {
! 12: my ( $self, $action ) = @_;
! 13:
! 14: state $Actions = {
! 15: location => { mtime => 0 },
! 16: speakers => { mtime => 0 },
! 17: talks => { mtime => 0 },
! 18: interests => { mtime => 0 },
! 19: users => { mtime => 0 },
! 20: };
! 21: return if !exists $Actions->{$action};
! 22:
! 23: my $path = app->home->rel_file( 'data/' . $action );
! 24: my $mtime = ( stat $path )[9];
! 25:
! 26: if ( $mtime != $Actions->{$action}{mtime} ) {
! 27: open my $fh, $path or die "Couldn't open [$path]: $!";
! 28: my $content = do { local $/; <$fh> };
! 29: close $fh;
! 30:
! 31: my $json = Mojo::JSON->new;
! 32: my $data = $json->decode($content);
! 33: if ( $json->error ) {
! 34: die $json->error;
! 35: }
! 36:
! 37: $Actions->{$action} = {
! 38: mtime => $mtime,
! 39: data => $data,
! 40: };
! 41: }
! 42:
! 43: return $Actions->{$action}{data};
! 44: }
1.1 andrew 45: );
46:
47: get '/' => 'index';
48:
49: get '/api/:action' => sub {
1.2 ! andrew 50: my $self = shift;
1.1 andrew 51:
1.2 ! andrew 52: my $data = $self->helper( 'action', $self->stash('action') );
! 53: return if !ref $data;
1.1 andrew 54:
1.2 ! andrew 55: my @data = @{$data};
! 56: foreach my $param ( $self->param ) {
1.1 andrew 57: my $value = $self->param($param);
1.2 ! andrew 58: @data = grep { ( !exists $_->{$param} ) || $value ~~ $_->{$param} }
! 59: @data;
1.1 andrew 60: }
61: $self->render_json( \@data );
62: };
63:
64: app->start;
65: __DATA__
66:
67: @@ index.html.ep
68: % layout 'default';
69: Please try /api/action
70:
71: @@ layouts/default.html.ep
72: <!doctype html><html>
73: <head><title>Test OpenAMD API!</title></head>
74: <body><%== content %></body>
1.2 ! andrew 75: </html>
! 76:
! 77: @@ exception.html.ep
! 78: <!doctype html><html>
! 79: <head><title>Exception</title></head>
! 80: <body><%== $exception %></body>
1.1 andrew 81: </html>
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>