Search code examples
socketslualuasocket

Lua socket error on connection


I'm trying to make a http get, using Lua Socket:

local client = socket.connect('warm-harbor-2019.herokuapp.com',80)
if client then
    client:send("GET /get_tweets HTTP/1.0\r\n\r\n")
      s, status, partial = client:receive(1024)
    end
end

I expect s to be a tweet, since the get that I'm making returns one. But I'm getting:

http/1.1 404 object not found

Solution

  • Here is a runnable version of your code example (that exhibit the problem you described):

    local socket = require "socket"
    local client = socket.connect('warm-harbor-2019.herokuapp.com',80)
    if client then
        client:send("GET /get_tweets HTTP/1.0\r\n\r\n")
        local s, status, partial = client:receive(1024)
        print(s)
    end
    

    If you read the error page returned, you can see that its title is Heroku | No such app.

    The reason for that is that the Heroku router only works when a Host header is provided. The easiest way to do it is to use the actual HTTP module of LuaSocket instead of TCP directly:

    local http = require "socket.http"
    local s, status, headers = http.request("http://warm-harbor-2019.herokuapp.com/get_tweets")
    print(s)
    

    If you cannot use socket.http you can pass the Host header manually:

    local socket = require "socket"
    local client = socket.connect('warm-harbor-2019.herokuapp.com',80)
    client:send("GET /get_tweets HTTP/1.0\r\nHost: warm-harbor-2019.herokuapp.com\r\n\r\n")
    local s, status, partial = client:receive(1024)
    print(s, status, partial)
    

    With my version of LuaSocket, s will be nil, status will be "closed" and partial will contain the full HTTP response (with headers etc).