root/WWW-OpenSearch/branches/WWW-OpenSearch-rewrite/lib/WWW/OpenSearch.pm

Revision 1802 (checked in by bricas, 15 years ago)

Initial Import of rewrite branch

Line 
1 package WWW::OpenSearch;
2
3 use strict;
4 use warnings;
5
6 use base qw( Class::Accessor::Fast );
7
8 use Carp;
9 use LWP::UserAgent;
10 use WWW::OpenSearch::Response;
11 use WWW::OpenSearch::Description;
12
13 __PACKAGE__->mk_accessors( qw( description_url agent description ) );
14
15 our $VERSION = '0.06';
16
17 sub new {
18     my( $class, $url ) = @_;
19    
20     croak( "No OpenSearch Description url provided" ) unless $url;
21    
22     my $self = $class->SUPER::new;
23
24     $self->description_url( $url );
25     $self->agent( LWP::UserAgent->new( agent => join( '/', ref $self, $VERSION ) ) );
26
27     $self->fetch_description;
28    
29     return $self;
30 }
31
32 sub fetch_description {
33     my( $self, $url ) = @_;
34     $url ||= $self->description_url;
35     $self->description_url( $url );
36     my $response = $self->agent->get( $url );
37    
38     unless( $response->is_success ) {
39         croak "Error while fetching $url: " . $response->status_line;
40     }
41
42     $self->description( WWW::OpenSearch::Description->new( $response->content ) );
43 }
44
45 sub search {
46     my( $self, $query, $params ) = @_;
47
48     $params ||= { };
49     $params->{ searchTerms } = $query;
50    
51     my $url = $self->description->get_best_url;
52     return $self->do_search( $url->prepare_query( $params ), $url->method );
53 }
54
55 sub do_search {
56     my( $self, $url, $method ) = @_;
57    
58     $method = lc( $method ) || 'get';
59    
60     my $response;
61     if( $method eq 'post' ) {
62         my %form = $url->query_form;
63         $url->query_form( { } );
64         $response = $self->agent->post( $url, \%form );
65     }
66     else {
67         $response = $self->agent->$method( $url );
68     }
69    
70     return WWW::OpenSearch::Response->new( $self, $response );   
71 }
72
73 1;
Note: See TracBrowser for help on using the browser.