1 package HTTP::Body::Parser;
6 use base 'Class::Accessor::Fast';
10 use HTTP::Headers qw[];
11 use Params::Validate qw[];
13 __PACKAGE__->mk_accessors( qw[ bufsize context seen_eos ] );
18 my ( $content_type, $parser ) = ( @_ == 2 ) ? @_[ 1, 0 ] : @_[ 1, 2 ];
20 $PARSERS->{ $content_type } = $parser;
22 eval "use prefork '$parser';";
25 __PACKAGE__->register_parser( 'application/octet-stream' => 'HTTP::Body::Parser::OctetStream' );
26 __PACKAGE__->register_parser( 'application/x-www-form-urlencoded' => 'HTTP::Body::Parser::UrlEncoded' );
27 __PACKAGE__->register_parser( 'multipart/form-data' => 'HTTP::Body::Parser::MultiPart' );
44 my $class = ref $_[0] ? ref shift : shift;
45 my $params = Params::Validate::validate_with(
49 type => Params::Validate::SCALAR,
54 type => Params::Validate::OBJECT,
55 isa => 'HTTP::Body::Context',
59 called => "$class\::new"
63 if ( $class ne __PACKAGE__ ) {
64 return bless( {}, $class )->initialize($params);
68 my $content_type = $params->{context}->content_type;
70 Carp::croak qq/Mandatory header 'Content-Type' is missing from headers in context./
71 unless defined $content_type;
73 my $parser = $PARSERS->{ lc $content_type } || $PARSERS->{ 'application/octet-stream' };
75 eval "require $parser;"
76 or Carp::croak qq/Failed to load parser '$parser' for Content-Type '$content_type'. Reason '$@'/;
78 return $parser->new($params);
82 my ( $self, $params ) = @_;
84 $params->{buffer} = '';
85 $params->{length} = 0;
86 $params->{seen_eos} = 0;
88 while ( my ( $param, $value ) = each( %{ $params } ) ) {
89 $self->$param($value);
99 $self->{buffer} = $_[0];
105 sub length : lvalue {
109 $self->{length} = $_[0];
120 if ( $self->context->content_length ) {
122 my $expected = $self->context->content_length;
123 my $length = $self->length;
125 if ( $length < $expected ) {
126 Carp::croak qq/Truncated body. Expected $expected bytes, but only got $length bytes./;
136 if ( defined $_[0] ) {
137 $self->length += bytes::length $_[0];
138 $self->buffer .= $_[0];
148 Christian Hansen, C<ch@ngmedia.com>
150 This pod written by Ash Berlin, C<ash@cpan.org>.
154 This library is free software. You can redistribute it and/or modify
155 it under the same terms as perl itself.