Skip to content

Commit 5ae22b1

Browse files
committed
Merge branch 'master' of github.com:pintsized/lua-resty-http
2 parents aa48948 + 8929f8a commit 5ae22b1

File tree

1 file changed

+42
-5
lines changed

1 file changed

+42
-5
lines changed

README.md

Lines changed: 42 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,8 @@ lua_package_path "/path/to/lua-resty-http/lib/?.lua;;";
1515
server {
1616
location /simpleinterface {
1717
content_by_lua '
18+
1819
-- For simple work, use the URI interface...
19-
2020
local httpc = http.new()
2121
local res, err = httpc:request_uri("http://example.com/helloworld", {
2222
method = "POST",
@@ -29,7 +29,7 @@ server {
2929
-- In this simple form, there is no manual connection step, so the body is read
3030
-- all in one go, including any trailers, and the connection closed or keptalive
3131
-- for you.
32-
32+
3333
ngx.status = res.status
3434

3535
for k,v in pairs(res.headers) do
@@ -46,12 +46,10 @@ server {
4646
local httpc = http.new()
4747

4848
-- The generic form gives us more control. We must connect manually...
49-
5049
httpc:set_timeout(500)
5150
httpc:connect("127.0.0.1", 80)
5251

5352
-- And request using a path, rather than a full URI...
54-
5553
local res, err = httpc:request{
5654
path = "/helloworld",
5755
headers = {
@@ -70,11 +68,14 @@ server {
7068
--
7169
end
7270

71+
-- METHOD 1.
7372
-- At this point, the body has not been read. You can read it in one go
7473
-- if you like...
7574
local body = res:read_body()
7675

77-
-- or, stream the body using an iterator, for predictable memory usage
76+
77+
-- METHOD 2.
78+
-- Or, stream the body using an iterator, for predictable memory usage
7879
-- in Lua land.
7980
local reader = res.body_reader
8081

@@ -90,6 +91,42 @@ server {
9091
end
9192
until not chunk
9293

94+
95+
-- METHOD 3.
96+
-- Or, introduce your own coroutine filter to modify the chunks as they arrive.
97+
function get_filter(reader)
98+
return coroutine.wrap(function(max_bytes)
99+
repeat
100+
local chunk, err = reader(max_bytes)
101+
if not chunk then
102+
coroutine.yield(nil, err)
103+
break
104+
end
105+
106+
-- Process data
107+
108+
coroutine.yield(chunk)
109+
until not chunk
110+
end)
111+
end
112+
113+
-- pass the body reader to your filter
114+
local reader = get_filter(res.body_reader)
115+
116+
-- then read via your filter(s) as above
117+
repeat
118+
local chunk, err = reader(8192)
119+
if err then
120+
ngx.log(ngx.ERR, err)
121+
break
122+
end
123+
124+
if chunk then
125+
ngx.print(chunk)
126+
end
127+
until not chunk
128+
129+
93130
-- If the response advertised trailers, you can merge them with the headers now
94131
res:read_trailers()
95132

0 commit comments

Comments
 (0)