-
Notifications
You must be signed in to change notification settings - Fork 4
/
WWW.pm6
79 lines (71 loc) · 2.32 KB
/
WWW.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
67
68
69
70
71
72
73
74
75
76
77
78
79
unit module WWW;
use JSON::Fast;
use HTTP::UserAgent;
sub jget (|c) is export(:DEFAULT, :extras) {
CATCH { .fail }; from-json get |c
}
sub jpost (|c) is export(:DEFAULT, :extras) {
CATCH { .fail }; from-json post |c
}
sub jput (|c) is export(:extras) { CATCH { .fail }; from-json put |c }
sub jdelete (|c) is export(:extras) { CATCH { .fail }; from-json delete |c }
sub get ($url, *%headers) is export(:DEFAULT, :extras) {
CATCH { .fail }
%headers<User-Agent> //= 'Rakudo WWW';
with HTTP::UserAgent.new.get: $url, |%headers {
.is-success or fail .&err;
.decoded-content
}
}
proto post (|) is export(:DEFAULT, :extras) {*}
multi post ($url, *%form) is export(:DEFAULT, :extras) {
post $url, %, |%form
}
multi post ($url, %headers, *%form) is export(:DEFAULT, :extras) {
CATCH { .fail }
%headers<User-Agent> //= 'Rakudo WWW';
with HTTP::UserAgent.new.post($url, %form, |%headers) {
.is-success or fail .&err;
.decoded-content
}
}
multi post ($url, Str:D $json, *%headers) is export(:DEFAULT, :extras) {
CATCH { .fail }
%headers<User-Agent> //= 'Rakudo WWW';
my $req = HTTP::Request.new: POST => $url, |%headers;
$req.add-content: $json;
with HTTP::UserAgent.new.request($req) {
.is-success or fail .&err;
.decoded-content;
}
}
proto put (|) is export(:extras) {*}
multi put ($url, *%form) is export(:extras) { put $url, %, |%form }
multi put ($url, %headers, *%form) is export(:extras) {
CATCH { .fail }
%headers<User-Agent> //= 'Rakudo WWW';
with HTTP::UserAgent.new.put($url, %form, |%headers) {
.is-success or fail .&err;
.decoded-content
}
}
multi put ($url, Str:D $json, *%headers) is export(:extras) {
CATCH { .fail }
%headers<User-Agent> //= 'Rakudo WWW';
my $req = HTTP::Request.new: PUT => $url, |%headers;
$req.add-content: $json;
with HTTP::UserAgent.new.request($req) {
.is-success or fail .&err;
.decoded-content;
}
}
sub delete ($url, *%headers) is export(:extras) {
CATCH { .fail }
%headers<User-Agent> //= 'Rakudo WWW';
with HTTP::UserAgent.new.delete: $url, |%headers {
.code == 204 and return ''; # "204 No Content"
.is-success or fail .&err;
.decoded-content
}
}
sub err ($_) { "Error {.code}: {.status-line}" }