在 Bun 中通過 unix 域套接字進行 fetch
在 Bun 中,fetch() 可以通過 unix 選項,使用 unix 域套接字傳送 HTTP 請求。
const unix = "/var/run/docker.sock";
const response = await fetch("http://localhost/info", { unix });
const body = await response.json();
console.log(body); // { ... }
unix 選項是 unix 域套接字的本地檔案路徑。fetch() 會通過該套接字傳送請求,而不是使用 TCP 連線。也支援 HTTPS:在 URL 中使用 https:// 協議,而不是 http://。
要通過 unix 域套接字傳送 POST 請求到 API 端點:
const response = await fetch("https://hostname/a/path", {
unix: "/var/run/path/to/unix.sock",
method: "POST",
body: JSON.stringify({ message: "Hello from Bun!" }),
headers: {
"Content-Type": "application/json",
},
});
const body = await response.json();