Skip to content

Instantly share code, notes, and snippets.

@dol
Created December 19, 2022 23:00
Show Gist options
  • Save dol/134e167a2341e6f4e74666b79f7b509e to your computer and use it in GitHub Desktop.
Save dol/134e167a2341e6f4e74666b79f7b509e to your computer and use it in GitHub Desktop.
Chunked encoding in Lua
function chunked_encoding(socket, data)
local chunk_size = 1024
-- Iterate over the data in chunks of chunk_size
for i = 1, #data, chunk_size do
local chunk = data:sub(i, i + chunk_size - 1)
-- Calculate the length of the chunk in hexadecimal format
local length = string.format("%X\r\n", #chunk)
-- Prefix the chunk with the length and CR LF characters
local encoded_chunk = length .. chunk .. "\r\n"
-- Send the encoded chunk to the socket
socket:send(encoded_chunk)
end
-- Send a final chunk with a length of "0" to indicate the end of the chunked encoding
socket:send("0\r\n")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment