Search code examples
lualuasocketluarocks

Capture full response in Lua Socket call


I am trying to call a REST API through LUA. However, I am not able to capture full raw response returned by the API. Below is the code sample:

local http_socket = require("socket.http")
local pretty_print = require("pl.pretty")
local header = {
                 ["x-device-type"] = "M",
                 ["authorization"] = "ashdjkashd",
                 ["x-app-secret"] = "asdasda",
                 ["x-user-id"] = "asdasdasd"
                 }

r, c, h = http_socket.request {
       method = "GET",                          -- Validation API Method                           
       url = "http://google.com",   -- Validation API URL
       headers = header
}
print(r .. c)
pretty_print.dump(h)

I'm using lua 5.3, and luarocks version=2.4.1. In variable c i am getting code, and in h there are a few headers. I need to capture full response returned by the API.


Solution

  • As you may know, luasocket's http.request supports two forms of usage. I'm assuming you need the second form to customize the resty request for that particular API.

    In this case to capture the response body you'll need to use the sink field with ltn12.sink module. For example

    local ltn12 = require 'ltn12'
    
    -- ...
    
    local res = {}
    r, c, h, s = http_socket.request
    {
      method = "GET",               -- Validation API Method
      url = "http://google.com",    -- Validation API URL
      headers = header,
      sink = ltn12.sink.table(res)
    }
    
    res = table.concat(res)
    print(res)
    

    The table.concat is needed since the response could be comprised of multiple chunk sizes(appended to res as it's received).

    You can also write it out to file by replacing above with ltn12.sink.file, eg. using ltn12.sink.file(io.stdout) will dump the response to standard output.