Skip to content

Commit

Permalink
add RequestID middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
haarg committed Oct 12, 2024
1 parent 9c5f6e3 commit e4d58a7
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 0 deletions.
46 changes: 46 additions & 0 deletions lib/Plack/Middleware/MetaCPAN/RequestID.pm
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package Plack::Middleware::MetaCPAN::RequestID;
use strict;
use warnings;

our $VERSION = 'v1.0.1';

use Moo;

use Digest::SHA;

use namespace::clean;

with qw(MetaCPAN::Role::Middleware);

has env_key => (
is => 'ro',
required => 1,
);

sub call {
my ( $self, $env ) = @_;

$env->{ $self->env_key } = Digest::SHA::sha1_hex( join(
"\0", $env->{REMOTE_ADDR}, $env->{REQUEST_URI}, time, $$, rand, ) );

$self->app->($env);
}

1;
__END__
=pod
=encoding UTF-8
=for stopwords MDC
=head1 NAME
Plack::Middleware::MetaCPAN::RequestID - Generate a Request ID
=head1 ATTRIBUTES
=head2 env_key
=cut
1 change: 1 addition & 0 deletions t/basic.t
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use Catalyst::Plugin::MetaCPAN::Fastly;
use Plack::Middleware::MetaCPAN::ReverseProxy;
use Plack::Middleware::MetaCPAN::L4PContext;
use Plack::Middleware::MetaCPAN::CSP;
use Plack::Middleware::MetaCPAN::RequestID;
use MetaCPAN::Role::Middleware;
use MetaCPAN::Common;
use MetaCPAN::Logger;
Expand Down
27 changes: 27 additions & 0 deletions t/requestid.t
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
use strict;
use warnings;

use Test::More;
use Data::Dumper ();
use Plack::Middleware::MetaCPAN::RequestID;
use HTTP::Request::Common qw(GET);
use Plack::Test qw(test_psgi);

my $app = sub {
my $env = shift;
[ 200, [], [ $env->{'request-id'} ] ];
};
$app = Plack::Middleware::MetaCPAN::RequestID->wrap(
$app,
{
env_key => 'request-id',
}
);

test_psgi $app, sub {
my $cb = shift;
my $res = $cb->( GET "/" );
like $res->content, qr/\A[a-zA-Z0-9]{40}\z/, 'has a request id';
};

done_testing;

0 comments on commit e4d58a7

Please sign in to comment.