| 1 | package MYDan::Project::Check::Http; | ||
| 2 | use strict; | ||
| 3 | use warnings; | ||
| 4 | use Carp; | ||
| 5 | use Encode; | ||
| 6 | |||
| 7 | use LWP::UserAgent; | ||
| 8 | |||
| 9 | # addr: http://localhost/stat | ||
| 10 | # check: 'ok' | ||
| 11 | # type: post # type: get default | ||
| 12 | # data: a=1&b=2 | ||
| 13 | # Host: abc.org | ||
| 14 | |||
| 15 | sub new | ||
| 16 | { | ||
| 17 | my ( $class, %self ) = @_; | ||
| 18 | $self{check} ||=''; | ||
| 19 | map{ | ||
| 20 | confess "$_ undef.\n" unless defined $self{$_}; | ||
| 21 | Encode::_utf8_off( $self{$_} ); | ||
| 22 | }qw( addr check ); | ||
| 23 | my %opt = $self{addr} =~ /^https/ ? ( ssl_opts => { verify_hostname => 0 } ) :(); | ||
| 24 | |||
| 25 | $self{ua} = my $ua = LWP::UserAgent->new( %opt ); | ||
| 26 | $ua->agent('Mozilla/9 [en] (Centos; Linux)'); | ||
| 27 | $ua->timeout( 10 ); | ||
| 28 | $ua->default_header ( 'Cache-control' => 'no-cache', 'Pragma' => 'no-cache', Host => $self{Host} ); | ||
| 29 | |||
| 30 | $self{type} ||= 'get'; | ||
| 31 | |||
| 32 | bless \%self, ref $class || $class; | ||
| 33 | } | ||
| 34 | |||
| 35 | sub check | ||
| 36 | { | ||
| 37 | my $this = shift; | ||
| 38 | my ( $ua, $addr, $check, $data, $type ) = @$this{qw( ua addr check data type )}; | ||
| 39 | |||
| 40 | my $res = $type eq 'post' | ||
| 41 | ? $ua->post( $addr, $data ? ( Content => $data ) : () ) | ||
| 42 | : $ua->get( $addr ); | ||
| 43 | |||
| 44 | my $content = $res->is_success ? $res->content : die "$addr not success\n"; | ||
| 45 | print "$content\n" if $ENV{NS_DEBUG}; | ||
| 46 | |||
| 47 | ( defined $content ) && ( $check eq '' || $content =~ /$check/ ) | ||
| 48 | ? print "$addr <> $check :OK\n" | ||
| 49 | : die "$addr <> $check :FAIL\n"; | ||
| 50 | |||
| 51 | return 1; | ||
| 52 | } | ||
| 53 | |||
| 54 | 1; | ||
| 55 | __END__ |