http_pool.nim 768 B

12345678910111213141516171819202122232425262728293031323334353637
  1. import asyncdispatch, httpclient
  2. type
  3. HttpPool* = ref object
  4. conns*: seq[AsyncHttpClient]
  5. var maxConns {.threadvar.}: int
  6. let keepAlive* = newHttpHeaders({
  7. "Connection": "Keep-Alive"
  8. })
  9. proc setMaxHttpConns*(n: int) =
  10. maxConns = n
  11. proc release*(pool: HttpPool; client: AsyncHttpClient) =
  12. if pool.conns.len >= maxConns:
  13. client.close()
  14. elif client != nil:
  15. pool.conns.insert(client)
  16. template use*(pool: HttpPool; heads: HttpHeaders; body: untyped): untyped =
  17. var c {.inject.}: AsyncHttpClient
  18. if pool.conns.len == 0:
  19. c = newAsyncHttpClient(headers=heads)
  20. else:
  21. c = pool.conns.pop()
  22. c.headers = heads
  23. try:
  24. body
  25. except ProtocolError:
  26. # Twitter closed the connection, retry
  27. body
  28. finally:
  29. pool.release(c)