This example provides a way to make HTTP requests using only RETRO.
First, some variables. I'll keep the socket handle in Socket and the number of bytes read in Read.
Since HTTP allows for a large number of response headers with various sizes and ordering, skipping them can be annoying. I do care about one: the Content-Length: result.
I'll track the number of sequential newlines in a variable named Seq, the value for Content-Length in Length, and then the current response line in Line.
As a bonus annoyance, HTTP doesn't limit the size of any particular header line, so I need to allocate enough space to cover anything it throws at me. Per a stackoverflow posting at https://stackoverflow.com/questions/686217/maximum-on-http-header-values I'll need at least 8KiB, so:
Then skipping the headers is a matter of reading lines until two newlines are encountered.
Now on to making the actual request to the server. An HTTP GET request takes a minimal form like:
GET
So I begin by writing a word to parse a URL. It'll store pointers to the
parts in the Host and Request variables. This is pretty easy. I
increase the starting point by 7 to skip over the HTTP:// part and then
split on the first / character to separate the domain and requested file.
Given that, making a request is simply:
Moving on to reading the body, this is just reading bytes and shoving
them into a buffer. I use the Read variable to track the number of
bytes read, stopping when this reaches the Length extracted from the
headers.
And finally tieing this all together:
And a test case: