Bun

指南HTTP

在 Bun 中使用 Unix Domain Socket 進行 Fetch

在 Bun 中,fetch()unix 選項讓您透過 Unix Domain Socket 發送 HTTP 請求。

const unix = "/var/run/docker.sock";

const response = await fetch("https://127.0.0.1/info", { unix });

const body = await response.json();
console.log(body); // { ... }

unix 選項是一個字串,用於指定 Unix Domain Socket 的本地檔案路徑。fetch() 函數將使用此 Socket 發送請求至伺服器,而非使用 TCP 網路連線。透過在 URL 中使用 https:// 協定而非 http://,也支援 https

要透過 Unix Domain Socket 發送 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();