Last active
November 18, 2017 06:13
-
-
Save dhcmrlchtdj/eabaa34a2f7bd33b0623f5ee6fff16a6 to your computer and use it in GitHub Desktop.
HTTP proxy in typescript. client --HTTP_PROXY--> local_proxy --HTTP_PROXY--> remote_proxy --> server
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 * as HTTP from 'http'; | |
| import * as URL from 'url'; | |
| import * as NET from 'net'; | |
| import * as ProxyAgent from 'proxy-agent'; | |
| export function createProxy(proxyURL: string): HTTP.Server { | |
| const agent: HTTP.Agent = new ProxyAgent(proxyURL); | |
| const proxyURLObj = URL.parse(proxyURL); | |
| const proxyServer = new HTTP.Server(); | |
| proxyServer.on( | |
| 'request', | |
| (req: HTTP.IncomingMessage, res: HTTP.OutgoingMessage) => { | |
| req.pipe(HTTP.request({ agent })).pipe(res); | |
| }, | |
| ); | |
| proxyServer.on( | |
| 'connect', | |
| ( | |
| req: HTTP.IncomingMessage, | |
| clientSocket: NET.Socket, | |
| clientHead: Buffer, | |
| ) => { | |
| const reqProxy = HTTP.request({ | |
| method: 'CONNECT', | |
| hostname: proxyURLObj.host, | |
| port: proxyURLObj.port, | |
| path: req.url, | |
| agent, | |
| }); | |
| reqProxy.end(); | |
| reqProxy.on( | |
| 'connect', | |
| ( | |
| _: HTTP.IncomingMessage, | |
| proxySocket: NET.Socket, | |
| proxyHead: Buffer, | |
| ) => { | |
| clientSocket.write( | |
| 'HTTP/1.1 200 Connection Established\r\n\r\n', | |
| ); | |
| clientSocket.write(proxyHead); | |
| proxySocket.pipe(clientSocket); | |
| proxySocket.write(clientHead); | |
| clientSocket.pipe(proxySocket); | |
| }, | |
| ); | |
| reqProxy.on('error', e => { | |
| clientSocket.destroy(); // FIX | |
| console.error(`problem with request: ${e.message}`); | |
| }); | |
| }, | |
| ); | |
| proxyServer.on('error', e => { | |
| console.error(`problem with request: ${e.message}`); | |
| }); | |
| return proxyServer; | |
| } | |
| const example = async () => { | |
| const proxy = createProxy('http://example.com'); | |
| await new Promise(r => proxy.listen(0, '127.0.0.1', r)); | |
| const { address, port } = proxy.address(); | |
| const url = `http://${address}:${port}`; | |
| console.log(`proxy url: ${url}`); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment