openresty / lua-resty-upload

Streaming reader and parser for http file uploading based on ngx_lua cosocket
404 stars 113 forks source link

Iterator to work with generic for #48

Closed DarkWiiPlayer closed 5 years ago

DarkWiiPlayer commented 5 years ago

I noticed that the only way to receive the data seems to be to manually iterate until 'eof' is returned.

I think it would make sense to add a more user-friendly method that works with Luas generic for loop to iterate over the data.

Here's an example implementation:

function _M.each(self)
  return function(self)
    local type, data, err = self:read()
    if not type then
      error(err, 2)
    elseif type == "eof" then
    else
      return type, data
    end
  end, self
end

Then the example of the readme could also be written as

for type, data in form:each() do
  ngx.say("read: ", cjson.encode{type, data}
end
agentzh commented 5 years ago

@DarkWiiPlayer You can always wrap such an iterator API atop the existing API. Mind you, your for loop can be more expensive than the current API usage because it requires creating a new Lua function (for the iterator) which is a GC object.