Search code examples
luadownloadluasocket

Downloading a file using luasocket


I'm sorry if this has a simple solution, or if this has been resolved before, but I am so far removed from any kind of network programming that I really have no idea what is even wrong nor what to search for to fix it.

I would like to be able to download a json file from "https://api.coinbase.com/v2/exchange-rates" (and other places) using a language I know well, Lua, with the extension, luasocket.

I've tried using http.request and ftp.get, but neither returns any kind of information. I don't understand why I can go to that url on my browser, and it downloads a file, but I can't get the file data through luasocket. If I cannot use luasocket, then what are the differences between a request made from your web browser and a request made from something like luasocket?


Solution

  • As you may see the URL you have is https not plain http. You need to use encrypted connection. Use luasec for that instead of luasocket (actually luasec depends on luasocket but let's not bother for now; in short https.request from luasec is built on http.request from luasocket).

    local https = require "ssl.https" --luasec
    local r,c,h,s = https.request {
        url = "https://api.coinbase.com/v2/exchange-rates",
        sink = ltn12.sink.file(io.stdout)
    }
    

    This will print body of requested content in console.

    More about luasocket's http and luasec's https.