|
1 | 1 | import axios from 'axios'; |
2 | 2 | import http from 'http'; |
3 | 3 | import https from 'https'; |
| 4 | +import {ENV} from '../utils/env.js'; |
4 | 5 |
|
5 | 6 | const AgentOption = {keepAlive: true, maxSockets: 64, timeout: 30000}; // 最大连接数64,30秒定期清理空闲连接 |
6 | 7 | // const AgentOption = {keepAlive: true}; |
@@ -82,5 +83,45 @@ export default (fastify, options, done) => { |
82 | 83 | } |
83 | 84 | }); |
84 | 85 |
|
| 86 | + fastify.all('/req/*', async (request, reply) => { |
| 87 | + // 非VERCEL环境可在设置中心控制此功能是否开启 |
| 88 | + if (!process.env.VERCEL) { |
| 89 | + if (ENV.get('allow_forward') !== '1') { |
| 90 | + return reply.code(403).send({error: 'Forward api is not allowed by owner'}); |
| 91 | + } |
| 92 | + } |
| 93 | + try { |
| 94 | + const targetUrl = request.params['*']; |
| 95 | + if (!/^https?:\/\//.test(targetUrl)) { |
| 96 | + return reply.code(400).send({error: 'Invalid URL. Must start with http:// or https://'}); |
| 97 | + } |
| 98 | + console.log(`Forwarding request to: ${targetUrl}`); |
| 99 | + delete request.headers['host']; |
| 100 | + const response = await _axios({ |
| 101 | + method: request.method, |
| 102 | + url: targetUrl, |
| 103 | + headers: request.headers, |
| 104 | + data: request.body, |
| 105 | + params: request.query, |
| 106 | + timeout: 10000, |
| 107 | + }); |
| 108 | + |
| 109 | + reply |
| 110 | + .code(response.status) |
| 111 | + .headers(response.headers) |
| 112 | + .send(response.data); |
| 113 | + } catch (error) { |
| 114 | + console.error('Error forwarding request:', error.message); |
| 115 | + if (error.response) { |
| 116 | + reply |
| 117 | + .code(error.response.status) |
| 118 | + .headers(error.response.headers) |
| 119 | + .send(error.response.data); |
| 120 | + } else { |
| 121 | + reply.code(500).send({error: `Internal Server Error:${error.message}`}); |
| 122 | + } |
| 123 | + } |
| 124 | + }); |
| 125 | + |
85 | 126 | done(); |
86 | 127 | }; |
0 commit comments