quickjs/examples/http_client.js

26 lines
1.2 KiB
JavaScript
Raw Normal View History

2025-05-22 05:22:19 +00:00
#!/usr/bin/env qjs
///@ts-check
/// <reference path="../doc/globals.d.ts" />
/// <reference path="../doc/os.d.ts" />
2025-06-29 12:40:10 +00:00
/// <reference path="../doc/std.d.ts" />
2025-05-22 05:22:19 +00:00
import * as os from "os";
2025-06-29 12:40:10 +00:00
import * as std from "std";
2025-05-22 05:22:19 +00:00
/** @template T @param {os.Result<T>} result */
function must(result) {
2025-06-29 12:40:10 +00:00
if (typeof result === "number" && result < 0) throw new Error(std.strerror(-result));
2025-05-22 05:22:19 +00:00
return /** @type {T} */ (result)
}
2025-06-29 12:40:10 +00:00
//USAGE: client.js wttr.in/paris
const uriRegexp = /^(?<host>[A-Za-z0-9\-\.]+)(?<port>:[0-9]+)?(?<query>.*)$/;
const { host = "bellard.org", port = ":80", query = "/" } = scriptArgs[1]?.match(uriRegexp)?.groups || {};
console.log("sending GET on",{ host, port, query })
const [addr] = must(os.getaddrinfo(host, { service: port.slice(1) }));
const sockfd = must(os.socket(addr.family, addr.socktype));
2025-06-23 18:58:10 +00:00
await os.connect(sockfd, addr);
2025-06-29 12:40:10 +00:00
const httpReq = Uint8Array.from(`GET ${query||'/'} HTTP/1.0\r\nHost: ${host}\r\nUser-Agent: curl\r\n\r\n`, c => c.charCodeAt(0))
2025-06-23 18:58:10 +00:00
must(await os.send(sockfd, httpReq.buffer) > 0);
2025-05-22 05:22:19 +00:00
const chunk = new Uint8Array(512);
const recvd = await os.recv(sockfd, chunk.buffer);
2025-06-29 12:40:10 +00:00
console.log([...chunk.slice(0, recvd)].map(c => String.fromCharCode(c)).join(''));