Async iterators are [an open issue on the Nim 
github](https://github.com/nim-lang/Nim/issues/6576), so your concern is 
normal. Here is how you would do it in a template:
    
    
    template forStream(req: Request, chunkSize: int, body: untyped): untyped 
{.dirty.} = # dirty means all the variable names in the template are usable in 
the block
      var remainder = req.contentLength
      while true:
        let data = await req.client.recv(min(remainder, chunkSize))
        body
        remainder -= len(data)
        if remainder == 0:
          break
    
    proc cb(req: Request) {.async.} =
      var
        contentLength = 0
        bodyLength = 0
      if req.reqMethod == HttpPost:
        contentLength = req.headers["Content-length"].parseInt
        if stream:
          req.forStream(8*1024):
            echo data
            bodyLength += len(data)
        else:
          bodyLength += req.body.len
      
      await req.respond(Http200, htmlpage(contentLength, bodyLength))
    
    
    Run

If you want the variable name to be customizable and not just data, you can use 
identifier construction in templates:
    
    
    template forStream(req: Request, chunkSize: int, name, body: untyped): 
untyped =
      var remainder = req.contentLength
      while true:
        let `name` = await req.client.recv(min(remainder, chunkSize))
        body
        remainder -= len(`name`)
        if remainder == 0:
          break
    
    req.forStream(8*1024, d):
      echo d
    
    
    Run

Reply via email to