@@ -15,8 +15,8 @@ lua_package_path "/path/to/lua-resty-http/lib/?.lua;;";
15
15
server {
16
16
location / simpleinterface {
17
17
content_by_lua '
18
+
18
19
-- For simple work, use the URI interface...
19
-
20
20
local httpc = http .new ()
21
21
local res , err = httpc :request_uri (" http://example.com/helloworld" , {
22
22
method = " POST" ,
@@ -29,7 +29,7 @@ server {
29
29
-- In this simple form, there is no manual connection step, so the body is read
30
30
-- all in one go, including any trailers, and the connection closed or keptalive
31
31
-- for you.
32
-
32
+
33
33
ngx .status = res .status
34
34
35
35
for k ,v in pairs (res .headers ) do
@@ -46,12 +46,10 @@ server {
46
46
local httpc = http .new ()
47
47
48
48
-- The generic form gives us more control. We must connect manually...
49
-
50
49
httpc :set_timeout (500 )
51
50
httpc :connect (" 127.0.0.1" , 80 )
52
51
53
52
-- And request using a path, rather than a full URI...
54
-
55
53
local res , err = httpc :request {
56
54
path = " /helloworld" ,
57
55
headers = {
@@ -70,11 +68,14 @@ server {
70
68
--
71
69
end
72
70
71
+ -- METHOD 1.
73
72
-- At this point, the body has not been read. You can read it in one go
74
73
-- if you like...
75
74
local body = res :read_body ()
76
75
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
78
79
-- in Lua land.
79
80
local reader = res .body_reader
80
81
@@ -90,6 +91,42 @@ server {
90
91
end
91
92
until not chunk
92
93
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
+
93
130
-- If the response advertised trailers, you can merge them with the headers now
94
131
res :read_trailers ()
95
132
0 commit comments