fetch-h2 是一个不错的库,但官方没给使用代理的例子,Issues也有有人提,但没人答,自己用其他库的方法又行不通。简单研究下,大概弄明白了。
突破点是tls.connect初始化时支持同个options 传入指定socket
// https://github.com/grantila/fetch-h2/blob/80c720197ba42a203140509e0442dc52703afada/lib/context-https.ts#L57
const socket: TLSSocket = connect( parseInt( port, 10 ), host, opts,
import {context} from 'fetch-h2'
import {SocksClient} from 'socks';
// SOCKS5 proxy configuration
const proxyOptions = {
proxy: {
host: '127.0.0.1', // e.g., '127.0.0.1'
port: 1081, // Default SOCKS5 port
type: 5, // SOCKS5 (use 4 for SOCKS4)
// Add username/password if required
// userId: 'user',
// password: 'pass'
},
destination: {
host: 'proxyguess.bjun.tech', // Target server host
port: 9766 // Target server port (TLS)
},
command: 'connect' // Establish a TCP connection through the proxy
};
const {socket: proxySocket} = await SocksClient.createConnection(proxyOptions);
const ctx0 = context({
HttpProtocols: 'http2', session: {
socket: proxySocket
}
});
const response = await ctx0.fetch('https://proxyguess.bjun.tech:9766/proxy_check_ez', {});
console.log(await response.text());
/*
{
"tcp_rtt": "0.404",
"h2_rtt": 292.14,
"guess use proxy": "100%"
}
*/
import {context} from 'fetch-h2'
import { SocksClient } from 'socks';
export async function h2_proxy(proxy,server_host){
// SOCKS5 proxy configuration
const proxyOptions = {
proxy: proxy,
destination: {
host: server_host, // Target server host
port: 443 // Target server port (TLS)
},
command: 'connect' // Establish a TCP connection through the proxy
};
const { socket: proxySocket } = await SocksClient.createConnection(proxyOptions);
return context({HttpProtocols: 'http2',session:{
socket: proxySocket
}})
}
https://nodejs.org/api/tls.html#tlsconnectoptions-callback
https://github.com/grantila/fetch-h2