app.psgi 1.0 KB

123456789101112131415161718192021222324252627
  1. use strict; use feature 'state';
  2. use JSON::XS 'encode_json';
  3. use DBI;
  4. use List::Util qw'min max';
  5. sub {
  6. state $dbh = DBI->connect(
  7. 'dbi:mysql:database=hello_world;host=tfb-database;port=3306',
  8. 'benchmarkdbuser', 'benchmarkdbpass',
  9. +{ qw'RaiseError 0 PrintError 0 mysql_enable_utf8 1' }
  10. ) || die $!;
  11. state $sth = $dbh->prepare('select id,randomnumber from world where id = ?');
  12. my $env = shift;
  13. my $path = $env->{PATH_INFO};
  14. return [200, [qw(Content-Type application/json)], [encode_json(+{ message => 'Hello, World!' })]] if $path eq '/json';
  15. return [200, [qw(Content-Type text/plain)], ['Hello, World!']] if $path eq '/plaintext';
  16. if ( $path eq '/db' ) {
  17. my ($n) = ($env->{QUERY_STRING} // '' ) =~ m/queries=(\d+)/;
  18. $n = max(1, min($n//1, 500));
  19. my @rs = map {
  20. $sth->execute(my $id = int(rand 10000) + 1);
  21. +{ id => $id, randomNumber => 0+ $sth->fetch->[0] }
  22. } 1..$n;
  23. return [ 200, [qw(Content-Type application/json)], [encode_json($env->{QUERY_STRING} ? \@rs : $rs[0] // {})]];
  24. }
  25. [ 404, [], ['not found']];
  26. }