9951 explained code solutions for 126 technologies


luaHow to create HTTP server


We'll create sample HTTP server in the file named srv.lua and launch it with lua srv.lua command. Press Ctrl+C to stop server.

local server = require 'http.server'
local headers = require 'http.headers'

local srv = server.listen {
  host = 'localhost',
  port = 82,
  onstream = function (sv, out)
    local hdrs = out:get_headers()
    local method = hdrs:get(':method')
    local path = hdrs:get(':path') or '/'

    local rh = headers.new()
    rh:append(':status','200')
    rh:append('content-type','text/plain')

    out:write_headers(rh, false)
    out:write_chunk(("Received '%s' request on '%s' at %s\n"):format(method, path, os.date()), true)
  end
}

srv:listen()
srv:loop()ctrl + c
require 'http.

loads lua-http module

server.listen

launch HTTP server to listen for requests

localhost

host to listen on

82

port to listen on

onstream

callback to process request and return response

method

request method

path

request path

out:write_headers

send headers to response

out:write_chunk

send text to response

srv:listen()

launch our HTTP server