Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save hagevvashi/7c30cec4622690fca638d7be2c454f58 to your computer and use it in GitHub Desktop.
Save hagevvashi/7c30cec4622690fca638d7be2c454f58 to your computer and use it in GitHub Desktop.
リバースプロキシの実装
async function apiReverseProxy(
apiBasePath: string,
clientReq: any,
clientRes: any
) {
return new Promise((resolve) => {
const serverReq = request({
// VMなどで実行されるならここはos.hostname()など環境に合わせること。幸いNode.jsなのでos.type()などを用いて柔軟に対応できる。
host: "localhost",
// stub serverのport番号をしていする。package.jsonのconfigで設定するのもよい
// process.env.npm_package_config_stub_server_portのような形で取得可能
port: 8000,
method: clientReq.method,
path: clientReq.url.slice(apiBasePath.length),
headers: clientReq.headers,
})
.on("error", () => {
clientRes.writeHead(502);
resolve();
})
.on("timeout", () => {
clientRes.writeHead(504).end();
resolve();
})
.on("response", (serverRes) => {
clientRes.writeHead(serverRes.statusCode, serverRes.headers);
serverRes.pipe(clientRes);
resolve();
});
clientReq.pipe(serverReq);
});
}
// routeの方からの呼び出しはこう
async function route(pathname: string, req: any, res: any) {
const apiBasePath = "/api";
if (pathname.startsWith(apiBasePath)) {
await apiReverseProxy(apiBasePath, req, res);
return;
}
// 省略
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment