-
-
Notifications
You must be signed in to change notification settings - Fork 648
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat(helper/proxy): introduce proxy helper #3589
Open
usualoma
wants to merge
16
commits into
honojs:main
Choose a base branch
from
usualoma:feat-helper-proxy
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+309
−0
Open
Changes from 5 commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
dcfa1a5
feat(helper/proxy): introduce proxy helper
usualoma 64cdd41
chore(helper/proxy): expose proxy helper
usualoma ad17d90
test(helper/proxy): fix test name
usualoma 5998770
fix(helper/proxy): return Content-Range header as it is
usualoma 3a5ef0f
refactor(helper/proxy): return the original content-length if the res…
usualoma b6eb510
feat(middleware): enable to pass `...c.req` to init options
usualoma fb54227
refactor(middleware/proxy): rename `proxyFetch` to `proxy`
usualoma e08c602
docs(helper/proxy): update example
usualoma eafc02a
docs(helper/proxy): fix typo
usualoma dc24de3
refactor(helper/proxy): also accept HonoRequest instance as request init
usualoma 833b8e2
fix(helper/proxy): remove hop-by-hop headers
usualoma d1ed0bd
Merge branch 'main' into feat-helper-proxy
usualoma 2e8e250
refactor(helper/proxy): build request init from request
usualoma 832532c
fix(helper/proxy): fix type error
usualoma e11a66d
test(helper/proxy): add test for modify header
usualoma 8a81633
fix(helper/proxy): It is generally the Set-Cookie that should be remo…
usualoma File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains 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
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,152 @@ | ||
import { Hono } from '../../hono' | ||
import { proxyFetch } from '.' | ||
|
||
describe('Proxy Middleware', () => { | ||
describe('proxyFetch', () => { | ||
beforeEach(() => { | ||
global.fetch = vi.fn().mockImplementation((req) => { | ||
if (req.url === 'https://example.com/compressed') { | ||
return Promise.resolve( | ||
new Response('ok', { | ||
headers: { | ||
'Content-Encoding': 'gzip', | ||
'Content-Length': '1', | ||
'Content-Range': 'bytes 0-2/1024', | ||
'X-Response-Id': '456', | ||
}, | ||
}) | ||
) | ||
} else if (req.url === 'https://example.com/uncompressed') { | ||
return Promise.resolve( | ||
new Response('ok', { | ||
headers: { | ||
'Content-Length': '2', | ||
'Content-Range': 'bytes 0-2/1024', | ||
'X-Response-Id': '456', | ||
}, | ||
}) | ||
) | ||
} | ||
return Promise.resolve(new Response('not found', { status: 404 })) | ||
}) | ||
}) | ||
|
||
it('compressed', async () => { | ||
const app = new Hono() | ||
app.get('/proxy/:path', (c) => | ||
proxyFetch( | ||
new Request(`https://example.com/${c.req.param('path')}`, { | ||
headers: { | ||
'X-Request-Id': '123', | ||
'Accept-Encoding': 'gzip', | ||
}, | ||
}) | ||
) | ||
) | ||
const res = await app.request('/proxy/compressed') | ||
const req = (global.fetch as ReturnType<typeof vi.fn>).mock.calls[0][0] | ||
|
||
expect(req.url).toBe('https://example.com/compressed') | ||
expect(req.headers.get('X-Request-Id')).toBe('123') | ||
expect(req.headers.get('Accept-Encoding')).toBeNull() | ||
|
||
expect(res.status).toBe(200) | ||
expect(res.headers.get('X-Response-Id')).toBe('456') | ||
expect(res.headers.get('Content-Encoding')).toBeNull() | ||
expect(res.headers.get('Content-Length')).toBeNull() | ||
expect(res.headers.get('Content-Range')).toBe('bytes 0-2/1024') | ||
}) | ||
|
||
it('uncompressed', async () => { | ||
const app = new Hono() | ||
app.get('/proxy/:path', (c) => | ||
proxyFetch( | ||
new Request(`https://example.com/${c.req.param('path')}`, { | ||
headers: { | ||
'X-Request-Id': '123', | ||
'Accept-Encoding': 'gzip', | ||
}, | ||
}) | ||
) | ||
) | ||
const res = await app.request('/proxy/uncompressed') | ||
const req = (global.fetch as ReturnType<typeof vi.fn>).mock.calls[0][0] | ||
|
||
expect(req.url).toBe('https://example.com/uncompressed') | ||
expect(req.headers.get('X-Request-Id')).toBe('123') | ||
expect(req.headers.get('Accept-Encoding')).toBeNull() | ||
|
||
expect(res.status).toBe(200) | ||
expect(res.headers.get('X-Response-Id')).toBe('456') | ||
expect(res.headers.get('Content-Length')).toBe('2') | ||
expect(res.headers.get('Content-Range')).toBe('bytes 0-2/1024') | ||
}) | ||
|
||
it('proxySetRequestHeaders option', async () => { | ||
const app = new Hono() | ||
app.get('/proxy/:path', (c) => | ||
proxyFetch( | ||
new Request(`https://example.com/${c.req.param('path')}`, { | ||
headers: { | ||
'X-Request-Id': '123', | ||
'X-To-Be-Deleted': 'to-be-deleted', | ||
'Accept-Encoding': 'gzip', | ||
}, | ||
}), | ||
{ | ||
proxySetRequestHeaders: { | ||
'X-Request-Id': 'abc', | ||
'X-Forwarded-For': '127.0.0.1', | ||
'X-Forwarded-Host': 'example.com', | ||
'X-To-Be-Deleted': undefined, | ||
}, | ||
} | ||
) | ||
) | ||
const res = await app.request('/proxy/compressed') | ||
const req = (global.fetch as ReturnType<typeof vi.fn>).mock.calls[0][0] | ||
|
||
expect(req.url).toBe('https://example.com/compressed') | ||
expect(req.headers.get('X-Request-Id')).toBe('abc') | ||
expect(req.headers.get('X-Forwarded-For')).toBe('127.0.0.1') | ||
expect(req.headers.get('X-Forwarded-Host')).toBe('example.com') | ||
expect(req.headers.get('X-To-Be-Deleted')).toBeNull() | ||
expect(req.headers.get('Accept-Encoding')).toBeNull() | ||
|
||
expect(res.status).toBe(200) | ||
expect(res.headers.get('X-Response-Id')).toBe('456') | ||
expect(res.headers.get('Content-Encoding')).toBeNull() | ||
expect(res.headers.get('Content-Length')).toBeNull() | ||
expect(res.headers.get('Content-Range')).toBe('bytes 0-2/1024') | ||
}) | ||
|
||
it('proxySetRequestHeaderNames option', async () => { | ||
const app = new Hono() | ||
app.get('/proxy/:path', (c) => | ||
proxyFetch( | ||
new Request(`https://example.com/${c.req.param('path')}`, { | ||
headers: { | ||
'X-Request-Id': '123', | ||
'Accept-Encoding': 'gzip', | ||
}, | ||
}), | ||
{ | ||
proxyDeleteResponseHeaderNames: ['X-Response-Id'], | ||
} | ||
) | ||
) | ||
const res = await app.request('/proxy/compressed') | ||
const req = (global.fetch as ReturnType<typeof vi.fn>).mock.calls[0][0] | ||
|
||
expect(req.url).toBe('https://example.com/compressed') | ||
expect(req.headers.get('X-Request-Id')).toBe('123') | ||
expect(req.headers.get('Accept-Encoding')).toBeNull() | ||
|
||
expect(res.status).toBe(200) | ||
expect(res.headers.get('X-Response-Id')).toBeNull() | ||
expect(res.headers.get('Content-Encoding')).toBeNull() | ||
expect(res.headers.get('Content-Length')).toBeNull() | ||
expect(res.headers.get('Content-Range')).toBe('bytes 0-2/1024') | ||
}) | ||
}) | ||
}) |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,82 @@ | ||
/** | ||
* @module | ||
* Proxy Helper for Hono. | ||
*/ | ||
|
||
// Typical header names for requests for proxy use | ||
type ProxyRequestHeaderName = 'X-Forwarded-For' | 'X-Forwarded-Proto' | 'X-Forwarded-Host' | ||
|
||
interface ProxyRequestInit extends RequestInit { | ||
/** | ||
* Headers that are overwritten in requests to the origin server. | ||
* Specify undefined to delete the header. | ||
*/ | ||
proxySetRequestHeaders?: Partial<Record<ProxyRequestHeaderName, string>> & | ||
Record<string, string | undefined> | ||
/** | ||
* Headers included in the response from the origin server that should be removed in the response to the client. | ||
*/ | ||
proxyDeleteResponseHeaderNames?: string[] | ||
} | ||
|
||
interface ProxyFetch { | ||
(input: RequestInfo | URL, init?: ProxyRequestInit): Promise<Response> | ||
(input: string | URL | globalThis.Request, init?: ProxyRequestInit): Promise<Response> | ||
} | ||
|
||
/** | ||
* Fetch API wrapper for proxy. | ||
* The parameters and return value are the same as for `fetch` (except for the proxy-specific options). | ||
* | ||
* The “Accept-Encoding” header is replaced with an encoding that the current runtime can handle. | ||
* Unnecessary response headers are deleted and a Response object is returned that can be returned | ||
* as is as a response from the handler. | ||
* | ||
* @example | ||
* ```ts | ||
* app.get('/proxy/:path', (c) => { | ||
* return proxyFetch(new Request(`http://${originServer}/${c.req.param('path')}`, c.req.raw), { | ||
* proxySetRequestHeaders: { | ||
* 'X-Forwarded-For': '127.0.0.1', | ||
* 'X-Forwarded-Host': c.req.header('host'), | ||
* Authorization: undefined, // do not propagate request headers contained in c.req.raw | ||
* }, | ||
* proxyDeleteResponseHeaderNames: ['Cookie'], | ||
* }) | ||
* }) | ||
* ``` | ||
*/ | ||
export const proxyFetch: ProxyFetch = async (input, proxyInit) => { | ||
const { | ||
proxySetRequestHeaders = {}, | ||
proxyDeleteResponseHeaderNames = [], | ||
...requestInit | ||
} = proxyInit ?? {} | ||
|
||
const req = new Request(input, requestInit) | ||
req.headers.delete('accept-encoding') | ||
|
||
for (const [key, value] of Object.entries(proxySetRequestHeaders)) { | ||
if (value !== undefined) { | ||
req.headers.set(key, value) | ||
} else { | ||
req.headers.delete(key) | ||
} | ||
} | ||
|
||
const res = await fetch(req) | ||
const resHeaders = new Headers(res.headers) | ||
if (resHeaders.has('content-encoding')) { | ||
resHeaders.delete('content-encoding') | ||
// Content-Length is the size of the compressed content, not the size of the original content | ||
resHeaders.delete('content-length') | ||
} | ||
for (const key of proxyDeleteResponseHeaderNames) { | ||
resHeaders.delete(key) | ||
} | ||
|
||
return new Response(res.body, { | ||
...res, | ||
headers: resHeaders, | ||
}) | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I like not using
new Request()
style like this:Then, if you have the following code:
you can also write it with not using
new Request()
style:These are short and user does not have to call
new Request()
. Both are okay, but I would like to write all cases in the code or examples with not usingnew Request()
style. What do you think of it?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@yusukebe
Sorry for the late reply. I understand your point.
I also think that it would be better not to show the
raw
part ofc.req.raw
if possible. I think that there is a risk in the statement that ‘all headers are transferred by default’, but I think that it would be best not to writeraw
.And,
because proxySetRequestHeaders
andproxyDeleteResponseHeaderNames
are also difficult to understand, I feel that it would be good to be able to write the following for proxies for GET requests.I wish it were possible to write a proxy for arbitrary requests, including POST, in a simpler way.