1 package Catalyst::TraitFor::Request::REST;
3 use HTTP::Headers::Util qw(split_header_words);
4 use namespace::autoclean;
6 has [qw/ data accept_only /] => ( is => 'rw' );
8 sub accepted_content_types {
11 return $self->{content_types} if $self->{content_types};
15 # First, we use the content type in the HTTP Request. It wins all.
16 $types{ $self->content_type } = 3
17 if $self->content_type;
19 if ($self->method eq "GET" && $self->param('content-type')) {
20 $types{ $self->param('content-type') } = 2;
23 # Third, we parse the Accept header, and see if the client
24 # takes a format we understand.
26 # This is taken from chansen's Apache2::UploadProgress.
27 if ( $self->header('Accept') ) {
28 $self->accept_only(1) unless keys %types;
30 my $accept_header = $self->header('Accept');
33 foreach my $pair ( split_header_words($accept_header) ) {
34 my ( $type, $qvalue ) = @{$pair}[ 0, 3 ];
35 next if $types{$type};
37 # cope with invalid (missing required q parameter) header like:
38 # application/json; charset="utf-8"
39 # http://tools.ietf.org/html/rfc2616#section-14.1
40 unless ( defined $pair->[2] && lc $pair->[2] eq 'q' ) {
44 unless ( defined $qvalue ) {
45 $qvalue = 1 - ( ++$counter / 1000 );
48 $types{$type} = sprintf( '%.3f', $qvalue );
52 return $self->{content_types} =
53 [ sort { $types{$b} <=> $types{$a} } keys %types ];
56 sub preferred_content_type { $_[0]->accepted_content_types->[0] }
62 return grep { $_ eq $type } @{ $self->accepted_content_types };