1

I've been trying now for a couple of hours to make a GET request to a simple page and then get the body as a result, but Luvit makes this incredibly complicated.

function httpGET()
    request = networking.get("https://google.com")
    local function callback(param)
      print(param)
    end
    request:done(callback)
end

After many iterations, this is as close as I have gotten (using this library https://github.com/cyrilis/luvit-request)

If someone with more experience would write a simple function to get the body of a page, I would really appreciate it. Thanks!

Reactified
  • 11
  • 1

1 Answers1

1

If you are using get from luvit/http then in callback you get IncomingMessage object as early as you get headers, and you must interpret data events yourself.

local http,https = require('http'),require('https')

function httpGET(url, callback)
    url = http.parseUrl(url)
    local req = (url.protocol == 'https' and https or http).get(url, function(res)
      local body={}
      res:on('data', function(s)
        body[#body+1] = s
      end)
      res:on('end', function()
        res.body = table.concat(body)
        callback(res)
      end)
      res:on('error', function(err)
        callback(res, err)
      end)
    end)
    req:on('error', function(err)
      callback(nil, err)
    end)
end

httpGET('http://example.com', function(res,err)
  if err then
    print('error', err)
  else  
    print(res.body)
  end
end)
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Darius
  • 1,060
  • 2
  • 6
  • 17