curly
curly copied to clipboard
streaming response prototype v2
import curly
let curl = newCurly()
let stream = curl.request("GET", "https://sse.dev/test", timeout = 5)
echo stream.code
echo stream.headers
try:
while true:
var buffer: string
let bytesRead = stream.read(buffer)
if bytesRead == 0:
break
echo buffer
finally:
stream.close()
echo "DONE"
- no callbacks
- get http status code, response headers, final url etc easily before committing to reading the body
- stream body in chucks with your own buffer (will append if buffer already has data in it)
If curl.request returns a stream to you (the call does not throw an exception), then you must call close on the stream when you are done.
Calling close is ok after a stream has been fully read or at any time before that to end a stream early.
Calling close is a dealloc call so calling close multiple times is not ok.
Calling close is necessary because the internal Curly thread handling the requests with libcurl has no way of knowing when you don't care about the request anymore.
The meaning of timeout is as follows: the stream must open (all headers received) within that number of seconds. After the headers have been received, curl.request returns a stream. Some number of bytes must arrive within the timeout seconds interval since the last read, or the stream will raise an exception from read as a timeout.