Created
June 1, 2018 03:57
-
-
Save userid/3f3ffaa85eb12967e0cd0a4d7c0f5ec0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env perl | |
| # | |
| use 5.010; | |
| use EV; | |
| use AnyEvent::Socket; | |
| use AnyEvent::Handle; | |
| $| = 1; | |
| sub http_get { | |
| my ($host, $uri, $cb) = @_; | |
| # store results here | |
| my ($response, $header, $body); | |
| my $handle; $handle = new AnyEvent::Handle | |
| connect => [$host => 'http'], | |
| on_error => sub { | |
| $cb->("HTTP/1.0 500 $!"); | |
| $handle->destroy; # explicitly destroy handle | |
| }, | |
| on_eof => sub { | |
| $cb->($response, $header, $body); | |
| $handle->destroy; # explicitly destroy handle | |
| }; | |
| $handle->push_write ("GET $uri HTTP/1.0\015\012\015\012"); | |
| # now fetch response status line | |
| $handle->push_read (line => sub { | |
| my ($handle, $line) = @_; | |
| $response = $line; | |
| }); | |
| # then the headers | |
| $handle->push_read (line => "\015\012\015\012", sub { | |
| my ($handle, $line) = @_; | |
| $header = $line; | |
| }); | |
| # and finally handle any remaining data as body | |
| $handle->on_read (sub { | |
| $body .= $_[0]->rbuf; | |
| $_[0]->rbuf = ""; | |
| }); | |
| } | |
| http_get "www.google.com", "/", sub { | |
| my ($response, $header, $body) = @_; | |
| $response, "\n", | |
| $body; | |
| }; | |
| EV::loop; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment