Http Server in Lua
Here’s the translation of the HTTP Server example from Go to Lua, formatted in Markdown suitable for Hugo:
Our HTTP server example demonstrates how to create a basic server using Lua and the luasocket
library.
local socket = require("socket")
local http = require("socket.http")
-- A fundamental concept in HTTP servers is handlers. In Lua, we can implement
-- handlers as functions that take a client socket as an argument.
function hello(client)
-- Functions serving as handlers take a client socket as an argument.
-- The handler is responsible for sending the HTTP response.
-- Here our simple response is just "hello\n".
client:send("HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\nhello\n")
end
function headers(client)
-- This handler does something a little more sophisticated by reading
-- all the HTTP request headers and echoing them into the response body.
local response = "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\n"
for line in client:receive("*l") do
if line == "" then break end
response = response .. line .. "\n"
end
client:send(response)
end
-- Create a TCP server
local server = assert(socket.bind("*", 8090))
print("Server listening on port 8090...")
while true do
-- Wait for a client connection
local client = server:accept()
-- Receive the request
local request = client:receive()
if request then
-- Parse the request to get the path
local _, _, method, path = string.find(request, "(%w+)%s+(.-)%s+HTTP")
-- Route the request to the appropriate handler
if path == "/hello" then
hello(client)
elseif path == "/headers" then
headers(client)
else
-- Default response for unknown routes
client:send("HTTP/1.1 404 Not Found\r\n\r\n")
end
end
-- Close the client connection
client:close()
end
To run the server:
$ lua http-server.lua
You can then access the server using curl:
$ curl localhost:8090/hello
hello
$ curl localhost:8090/headers
GET /headers HTTP/1.1
Host: localhost:8090
User-Agent: curl/7.68.0
Accept: */*
This Lua implementation provides similar functionality to the original example. It sets up a basic HTTP server that can handle requests to /hello
and /headers
paths. The server listens on port 8090 and uses a simple routing mechanism to direct requests to the appropriate handler function.
Note that this implementation uses a synchronous, single-threaded approach, which is suitable for demonstration purposes but may not be ideal for high-performance scenarios. For a production environment, you might want to consider using a more robust HTTP server library or implementing concurrency.