Last active
November 22, 2024 09:49
-
-
Save yusukebe/f3b04eb97bdec2f7e7f4b2ef1e48409d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Hono } from 'hono' | |
import type { Context } from 'hono' | |
interface ProxyFetch { | |
( | |
c: Context, | |
input: RequestInfo | URL, | |
modifyRequest: (req: Request) => void | undefined, | |
modifyResponse: (res: Response) => void | undefined | |
): Promise<Response> | |
} | |
const proxyFetch: ProxyFetch = async (c, input, modifyRequest, modifyResponse) => { | |
const req = new Request(input, c.req.raw) | |
req.headers.delete('accept-encoding') | |
const modifiedRequest = modifyRequest(req) ?? req | |
const fetchResponse = (await fetch(modifiedRequest)) as unknown as Response | |
const res = new Response(fetchResponse.body, fetchResponse) | |
res.headers.delete('content-encoding') | |
res.headers.delete('content-length') | |
const modifiedResposne = modifyResponse(res) ?? res | |
return modifiedResposne | |
} | |
const app = new Hono() | |
const origin = 'example.com' | |
app.get('/proxy/:path', async (c) => { | |
return proxyFetch( | |
c, | |
`http://${origin}/${c.req.param('path')}`, | |
(req) => req.headers.set('X-Forwarded-For', '127.0.0.1'), | |
(res) => res.headers.delete('Cookie') | |
) | |
}) | |
export default app |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment