29
30:- module(plweb_proxy,
31 [ proxy/2, 32 proxy/3 33 ]). 34:- use_module(library(http/http_open)). 35:- use_module(library(option)). 36:- use_module(library(apply)). 37
49
50proxy(To, Request) :-
51 proxy(To, Request, []).
52proxy(To, Request, Options) :-
53 memberchk(method(Method), Request),
54 proxy(Method, To, Request, Options).
55
56proxy(Method, To, Request, Options) :-
57 data_method(Method), !,
58 read_data(Request, Data),
59 memberchk(request_uri(URI), Request),
60 atomic_list_concat([To,URI], Target),
61 option(request_headers(ReqHrd0), Options, []),
62 maplist(request_header, ReqHrd0, ReqHrd),
63 http_open(Target, In,
64 [ method(Method),
65 post(Data),
66 header(content_type, ContentType)
67 | ReqHrd
68 ]),
69 call_cleanup(
70 read_string(In, _, Bytes),
71 close(In)),
72 option(reply_headers(HdrExtra0), Options, []),
73 maplist(reply_header, HdrExtra0, HdrExtra),
74 throw(http_reply(bytes(ContentType, Bytes), HdrExtra)).
75proxy(Method, To, Request, Options) :-
76 memberchk(request_uri(URI), Request),
77 atomic_list_concat([To,URI], Target),
78 option(request_headers(ReqHrd0), Options, []),
79 maplist(request_header, ReqHrd0, ReqHrd),
80 http_open(Target, In,
81 [ method(Method),
82 header(content_type, ContentType)
83 | ReqHrd
84 ]),
85 call_cleanup(
86 read_string(In, _, Bytes),
87 close(In)),
88 option(reply_headers(HdrExtra0), Options, []),
89 maplist(reply_header, HdrExtra0, HdrExtra),
90 throw(http_reply(bytes(ContentType, Bytes), HdrExtra)).
91
92read_data(Request, bytes(ContentType, Bytes)) :-
93 memberchk(input(In), Request),
94 memberchk(content_type(ContentType), Request),
95 ( memberchk(content_length(Len), Request)
96 -> read_string(In, Len, Bytes)
97 ; read_string(In, _, Bytes)
98 ).
99
100data_method(post).
101data_method(put).
102
(Name = Value, request_header(Name = Value)).
104
(Name = Value, Term) :-
106 Term =.. [Name,Value]