Files
lux/examples/http_server.lux
Brandon Lucas cdc4f47272 fix: fix REST API and HTTP server examples
- Fix string interpolation issues: escape curly braces with \{ and \}
  since unescaped { triggers string interpolation
- Fix effectful function invocation: use "let _ = run main() with {}"
  instead of bare "main()" calls
- Use inline record types instead of type aliases (structural typing)
- Fix flake.nix to show build progress instead of suppressing output

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-13 23:11:51 -05:00

45 lines
1.6 KiB
Plaintext

// HTTP Server Example
// Run with: cargo run -- examples/http_server.lux
// Then visit: http://localhost:8080/
// Simple request handler
fn handleRequest(req: { method: String, path: String, body: String, headers: List<(String, String)> }): Unit with {Console, HttpServer} = {
Console.print("Received: " + req.method + " " + req.path)
// Route based on path
match req.path {
"/" => HttpServer.respond(200, "Welcome to Lux HTTP Server!"),
"/hello" => HttpServer.respond(200, "Hello, World!"),
"/json" => HttpServer.respondWithHeaders(200, "\{\"message\": \"Hello from Lux!\"\}", [("Content-Type", "application/json")]),
"/echo" => HttpServer.respond(200, "You sent: " + req.body),
_ => HttpServer.respond(404, "Not Found: " + req.path)
}
}
// Handle N requests then stop
fn serveN(n: Int): Unit with {Console, HttpServer} =
if n <= 0 then {
Console.print("Server stopping...")
HttpServer.stop()
} else {
let req = HttpServer.accept()
handleRequest(req)
serveN(n - 1)
}
// Main entry point
fn main(): Unit with {Console, HttpServer} = {
let port = 8080
Console.print("Starting HTTP server on port " + toString(port) + "...")
HttpServer.listen(port)
Console.print("Server listening! Will handle 5 requests then stop.")
Console.print("Try: curl http://localhost:8080/")
Console.print(" curl http://localhost:8080/hello")
Console.print(" curl http://localhost:8080/json")
Console.print(" curl -X POST -d 'test data' http://localhost:8080/echo")
serveN(5)
}
// Run main
let output = run main() with {}