-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi-server.js
More file actions
249 lines (227 loc) · 7.45 KB
/
Copy pathapi-server.js
File metadata and controls
249 lines (227 loc) · 7.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
const express = require('express');
const ProxyPool = require('./proxy-pool');
/**
* Express API 服务
* 实现需求 4.1, 4.2, 4.3, 4.4, 4.5
*/
class ApiServer {
constructor(options = {}) {
this.app = express();
this.port = options.port || 3000;
this.proxyPool = new ProxyPool(options);
this.server = null;
this.setupMiddleware();
this.setupRoutes();
}
/**
* 配置 JSON 中间件
* 实现需求 4.1
*/
setupMiddleware() {
// 配置 JSON 中间件
this.app.use(express.json());
// 添加 CORS 支持
this.app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Content-Type');
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
next();
});
// 请求日志中间件 - 详细的请求日志记录
this.app.use((req, res, next) => {
const startTime = Date.now();
const timestamp = new Date().toISOString();
console.log(`📡 [${timestamp}] ${req.method} ${req.path} - 来自 ${req.ip || req.connection.remoteAddress}`);
// 记录响应时间
res.on('finish', () => {
const responseTime = Date.now() - startTime;
const statusEmoji = res.statusCode >= 400 ? '❌' : '✅';
console.log(`${statusEmoji} [${timestamp}] ${req.method} ${req.path} - ${res.statusCode} (${responseTime}ms)`);
});
next();
});
}
/**
* 设置 API 路由
* 实现需求 4.2, 4.3, 4.4
*/
setupRoutes() {
// GET /proxy 端点 - 返回一个可用代理或 503 错误
this.app.get('/proxy', (req, res) => {
try {
console.log('🎯 处理获取代理请求...');
const proxy = this.proxyPool.getProxy();
if (proxy) {
// 200 状态码表示成功,返回代理信息
console.log(`✅ 成功返回代理: ${proxy.ip}:${proxy.port}`);
res.status(200).json({
success: true,
data: {
ip: proxy.ip,
port: proxy.port,
protocol: proxy.protocol || 'http',
country: proxy.country || 'unknown',
anonymity: proxy.anonymity || 'unknown'
},
message: '成功获取代理'
});
} else {
// 503 状态码表示无可用代理
console.log('⚠️ 无可用代理,返回503状态');
res.status(503).json({
success: false,
error: '当前没有可用的代理',
code: 'NO_PROXY_AVAILABLE'
});
}
} catch (error) {
// 统一错误处理:记录详细错误信息但不终止程序
console.error('❌ 获取代理时发生错误:', error.message);
if (error.stack) {
console.error(' 错误堆栈:', error.stack.split('\n')[1]?.trim());
}
res.status(500).json({
success: false,
error: '服务器内部错误',
code: 'INTERNAL_ERROR'
});
}
});
// GET /status 端点 - 获取代理池状态
this.app.get('/status', (req, res) => {
try {
console.log('📊 处理获取状态请求...');
const status = this.proxyPool.getStatus();
console.log(`✅ 返回状态信息: ${status.totalProxies} 个代理`);
res.status(200).json({
success: true,
data: status,
message: '成功获取状态信息'
});
} catch (error) {
// 统一错误处理:记录详细错误信息但不终止程序
console.error('❌ 获取状态时发生错误:', error.message);
if (error.stack) {
console.error(' 错误堆栈:', error.stack.split('\n')[1]?.trim());
}
res.status(500).json({
success: false,
error: '服务器内部错误',
code: 'INTERNAL_ERROR'
});
}
});
// POST /refresh 端点 - 手动刷新代理池
this.app.post('/refresh', async (req, res) => {
try {
console.log('🔄 收到手动刷新代理池请求');
const startTime = Date.now();
const addedCount = await this.proxyPool.refresh();
const refreshTime = Date.now() - startTime;
console.log(`✅ 手动刷新完成: 添加了 ${addedCount} 个新代理,耗时 ${(refreshTime / 1000).toFixed(1)} 秒`);
res.status(200).json({
success: true,
data: {
addedProxies: addedCount,
totalProxies: this.proxyPool.getStatus().totalProxies,
refreshTime: refreshTime
},
message: `代理池刷新完成,添加了 ${addedCount} 个新代理`
});
} catch (error) {
// 统一错误处理:记录详细错误信息但不终止程序
console.error('❌ 刷新代理池时发生错误:', error.message);
if (error.stack) {
console.error(' 错误堆栈:', error.stack.split('\n')[1]?.trim());
}
res.status(500).json({
success: false,
error: '刷新代理池失败',
code: 'REFRESH_ERROR'
});
}
});
// 404 处理
this.app.use('*', (req, res) => {
res.status(404).json({
success: false,
error: '接口不存在',
code: 'NOT_FOUND'
});
});
// 全局错误处理中间件
this.app.use((error, req, res, next) => {
// 统一错误处理:记录详细错误信息但不终止程序
console.error('❌ 全局错误处理:', error.message);
if (error.stack) {
console.error(' 错误堆栈:', error.stack.split('\n').slice(0, 3).join('\n'));
}
console.error(` 请求路径: ${req.method} ${req.path}`);
console.error(` 请求来源: ${req.ip || req.connection.remoteAddress}`);
res.status(500).json({
success: false,
error: '服务器内部错误',
code: 'INTERNAL_ERROR'
});
});
}
/**
* 启动服务器
* 实现需求 4.5
* @returns {Promise<void>}
*/
async start() {
return new Promise((resolve, reject) => {
try {
this.server = this.app.listen(this.port, () => {
console.log(`🚀 代理池 API 服务已启动`);
console.log(`📡 服务地址: http://localhost:${this.port}`);
console.log(`📋 可用端点:`);
console.log(` GET /proxy - 获取一个可用代理`);
console.log(` GET /status - 获取代理池状态`);
console.log(` POST /refresh - 手动刷新代理池`);
console.log('');
resolve();
});
this.server.on('error', (error) => {
console.error('服务器启动失败:', error);
reject(error);
});
} catch (error) {
console.error('启动服务器时发生错误:', error);
reject(error);
}
});
}
/**
* 停止服务器
* @returns {Promise<void>}
*/
async stop() {
return new Promise((resolve) => {
if (this.server) {
this.server.close(() => {
console.log('API 服务器已停止');
resolve();
});
} else {
resolve();
}
});
}
/**
* 获取 Express 应用实例(用于测试)
* @returns {Express} Express 应用实例
*/
getApp() {
return this.app;
}
/**
* 获取代理池实例(用于测试)
* @returns {ProxyPool} 代理池实例
*/
getProxyPool() {
return this.proxyPool;
}
}
module.exports = ApiServer;