-
-
Notifications
You must be signed in to change notification settings - Fork 39
/
UserAgent.pm6
66 lines (49 loc) · 1.41 KB
/
UserAgent.pm6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
class HTTP::UserAgent;
use HTTP::Response;
use HTTP::Request;
use HTTP::UserAgent::Common;
class X::HTTP is Exception {
has $.rc;
}
class X::HTTP::Response is X::HTTP {
method message {
"Response error: '$.rc'";
}
}
class X::HTTP::Server is X::HTTP {
method message {
"Server error: '$.rc'";
}
}
has Int $.timeout is rw = 180;
has $.useragent;
method get(Str $url) {
my $request = HTTP::Request.new(GET => $url);
my $conn = IO::Socket::INET.new(:host($request.header('Host')), :port(80), :timeout($.timeout));
my $s;
if $conn.send($request.Str ~ "\r\n") {
$s = $conn.lines.join("\n");
}
$conn.close;
my $response = HTTP::Response.new.parse($s);
X::HTTP::Response.new(:rc($response.status-line)).throw
if $response.status-line.substr(0, 1) eq '4';
X::HTTP::Server.new(:rc($response.status-line)).throw
if $response.status-line.substr(0, 1) eq '5';
return $response;
}
# :simple
sub get(Str $url) is export(:simple) {
my $ua = HTTP::UserAgent.new;
my $response = $ua.get($url);
return $response.decoded-content;
}
sub head(Str $url) is export(:simple) {
my $ua = HTTP::UserAgent.new;
return $ua.get($url).headers.headers<Content-Type Document-Length Modified-Time Expires Server>;
}
sub getprint(Str $url) is export(:simple) {
my $response = get($url);
say $response;
# TODO: return response code
}