calog/examples/scripts/servers/httpServer.lua

23 lines
1,019 B
Lua

-- A polyglot HTTP server. Each route handler is a script function value; re-registering a route
-- hot-swaps it live while the server keeps serving. Handlers here are Lua, but a route handler can
-- be a function from ANY calog engine (and routes can share helpers via calogExport). The script
-- does not call calogExit, so its context stays alive to serve requests.
-- run: bin/calog examples/scripts/servers/httpServer.lua
-- then: curl localhost:8080/ curl localhost:8080/hello 'curl localhost:8080/echo?x=1'
local srv = httpdListen(8080)
httpdRoute(srv, "GET", "/", function(req)
return { status = 200, headers = { ["Content-Type"] = "text/plain" },
body = "calog httpd -- try /hello or /echo?name=ada\n" }
end)
httpdRoute(srv, "GET", "/hello", function(req)
return "hello from a Lua handler\n"
end)
httpdRoute(srv, "GET", "/echo", function(req)
return jsonStringify({ method = req.method, path = req.path, query = req.query })
end)
calogPrint("listening on http://localhost:8080")