Files
lux/examples/http.lux
2026-02-17 06:52:44 -05:00

73 lines
2.4 KiB
Plaintext

fn main(): Unit with {Console, Http} = {
Console.print("=== Lux HTTP Example ===")
Console.print("")
Console.print("Fetching data from httpbin.org...")
Console.print("")
match Http.get("https://httpbin.org/get") {
Ok(response) => {
Console.print("GET request successful!")
Console.print(" Status: " + toString(response.status))
Console.print(" Body length: " + toString(String.length(response.body)) + " bytes")
Console.print("")
match Json.parse(response.body) {
Ok(json) => {
Console.print("Parsed JSON response:")
match Json.get(json, "origin") {
Some(origin) => match Json.asString(origin) {
Some(ip) => Console.print(" Your IP: " + ip),
None => Console.print(" origin: (not a string)"),
},
None => Console.print(" origin: (not found)"),
}
match Json.get(json, "url") {
Some(url) => match Json.asString(url) {
Some(u) => Console.print(" URL: " + u),
None => Console.print(" url: (not a string)"),
},
None => Console.print(" url: (not found)"),
}
},
Err(e) => Console.print("JSON parse error: " + e),
}
},
Err(e) => Console.print("GET request failed: " + e),
}
Console.print("")
Console.print("--- POST Request ---")
Console.print("")
let requestBody = Json.object([("message", Json.string("Hello from Lux!")), ("version", Json.int(1))])
Console.print("Sending POST with JSON body...")
Console.print(" Body: " + Json.stringify(requestBody))
Console.print("")
match Http.postJson("https://httpbin.org/post", requestBody) {
Ok(response) => {
Console.print("POST request successful!")
Console.print(" Status: " + toString(response.status))
match Json.parse(response.body) {
Ok(json) => match Json.get(json, "json") {
Some(sentJson) => {
Console.print(" Server received:")
Console.print(" " + Json.stringify(sentJson))
},
None => Console.print(" (no json field in response)"),
},
Err(e) => Console.print("JSON parse error: " + e),
}
},
Err(e) => Console.print("POST request failed: " + e),
}
Console.print("")
Console.print("--- Headers ---")
Console.print("")
match Http.get("https://httpbin.org/headers") {
Ok(response) => {
Console.print("Response headers (first 5):")
let count = 0
Console.print(" Total headers: " + toString(List.length(response.headers)))
},
Err(e) => Console.print("Request failed: " + e),
}
}
let result = run main() with {}