app.pl 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #!/usr/bin/env perl
  2. use Web::Simple;
  3. use JSON::XS;
  4. use DBI;
  5. sub get_database_handle {
  6. DBI->connect_cached('dbi:mysql:database=hello_world;host=TFB-database', 'benchmarkdbuser', 'benchmarkdbpass', { RaiseError => 1 });
  7. }
  8. sub dispatch_request {
  9. sub (/json) {
  10. [ 200, [ 'Content-type' => 'application/json', ], [ encode_json({ message => 'Hello, World!' }) ] ];
  11. },
  12. sub (/db) {
  13. my ($id, $random_number);
  14. my $dbh = get_database_handle;
  15. my $sth = $dbh->prepare_cached('SELECT id, randomNumber FROM World where id = ?');
  16. $sth->execute(int(rand 10000) + 1);
  17. $sth->bind_columns(\$id, \$random_number);
  18. $sth->fetch;
  19. $sth->finish;
  20. [ 200, [ 'Content-type' => 'application/json', ], [ encode_json({ id => $id, randomNumber => $random_number })] ];
  21. },
  22. sub (/query + ?queries~) {
  23. my ($self, $queries) = @_;
  24. $queries //= 1;
  25. $queries = 1 if ($queries !~ /^\d+$/ || $queries < 1);
  26. $queries = 500 if $queries > 500;
  27. if ($queries == 1) {
  28. my ($id, $random_number);
  29. my $dbh = get_database_handle;
  30. my $sth = $dbh->prepare_cached('SELECT id, randomNumber FROM World where id = ?');
  31. $sth->execute(int(rand 10000) + 1);
  32. $sth->bind_columns(\$id, \$random_number);
  33. $sth->fetch;
  34. $sth->finish;
  35. [ 200, [ 'Content-type' => 'application/json', ], [ encode_json([{ id => $id, randomNumber => $random_number }])] ];
  36. }
  37. else {
  38. my @worlds;
  39. for (1 .. $queries) {
  40. my ($id, $random_number);
  41. my $dbh = get_database_handle;
  42. my $sth = $dbh->prepare_cached('SELECT id, randomNumber FROM World where id = ?');
  43. $sth->execute(int(rand 10000) + 1);
  44. $sth->bind_columns(\$id, \$random_number);
  45. $sth->fetch;
  46. $sth->finish;
  47. push @worlds, { id => $id, randomNumber => $random_number };
  48. }
  49. [ 200, [ 'Content-type' => 'application/json', ], [ encode_json(\@worlds)] ];
  50. }
  51. }
  52. }
  53. __PACKAGE__->run_if_script;