乐闻世界logo
搜索文章和话题

面试题手册

whistle 如何支持 WebSocket 代理和调试?

答案Whistle 提供了 WebSocket 代理功能,可以捕获、调试和修改 WebSocket 连接和消息。WebSocket 代理基础1. 基本 WebSocket 代理配置规则:ws://example.com host 127.0.0.1:8080wss://example.com host 127.0.0.1:8080或者使用 forward 操作符:ws://example.com forward ws://127.0.0.1:8080wss://example.com forward wss://127.0.0.1:80802. WebSocket 消息捕获Whistle 会自动捕获 WebSocket 连接和消息:连接建立:记录 WebSocket 握手信息消息发送:记录客户端发送的消息消息接收:记录服务器返回的消息连接关闭:记录连接关闭原因WebSocket 调试功能1. 查看消息详情在 whistle 管理界面中:点击 "Network" 标签筛选 "WS" 类型的请求点击 WebSocket 连接查看详情查看 "Messages" 标签中的消息历史2. 消息格式化Whistle 会自动格式化 JSON 消息:{ "type": "message", "data": { "id": 1, "content": "Hello" }}3. 消息过滤可以使用过滤器快速查找特定消息:按消息类型过滤按消息内容搜索按时间范围过滤WebSocket 消息修改1. 使用插件修改消息创建插件:websocket-modifier.jsmodule.exports = function(server, options) { server.on('upgrade', function(req, socket, head) { console.log('WebSocket upgrade:', req.url); }); server.on('connection', function(ws, req) { ws.on('message', function(message) { console.log('Received message:', message.toString()); // 修改消息 const modifiedMessage = modifyMessage(message); ws.send(modifiedMessage); }); });};function modifyMessage(message) { const data = JSON.parse(message.toString()); data.timestamp = Date.now(); return JSON.stringify(data);}配置规则:ws://example.com plugin://websocket-modifier2. 拦截和修改握手创建脚本:websocket-handshake.jsmodule.exports = function(req, res) { // 修改 WebSocket 握手头 if (req.headers['upgrade'] === 'websocket') { req.headers['X-Custom-Header'] = 'Custom Value'; }};配置规则:ws://example.com reqScript://{websocket-handshake.js}WebSocket 性能监控1. 连接时间监控Whistle 会记录 WebSocket 连接的各个阶段时间:DNS 解析时间TCP 连接时间SSL/TLS 握手时间(对于 wss)连接建立时间2. 消息统计消息数量:发送和接收的消息总数消息大小:消息的平均大小和总大小消息频率:消息发送和接收的频率3. 连接状态监控连接状态:连接是否活跃连接时长:连接持续时间重连次数:连接重连的次数WebSocket 调试技巧1. 模拟服务器响应创建脚本:websocket-mock.jsmodule.exports = function(server, options) { server.on('upgrade', function(req, socket, head) { console.log('Mock WebSocket server'); // 模拟服务器行为 socket.on('data', function(data) { console.log('Client message:', data.toString()); // 返回模拟响应 const response = JSON.stringify({ type: 'response', data: 'Mock response', timestamp: Date.now() }); socket.write(response); }); });};2. 消息延迟模拟创建脚本:websocket-delay.jsmodule.exports = function(server, options) { server.on('connection', function(ws, req) { ws.on('message', function(message) { // 模拟延迟 setTimeout(() => { ws.send(message); }, 1000); // 延迟 1 秒 }); });};3. 消息丢失模拟创建脚本:websocket-drop.jsmodule.exports = function(server, options) { let messageCount = 0; server.on('connection', function(ws, req) { ws.on('message', function(message) { messageCount++; // 每 10 条消息丢弃 1 条 if (messageCount % 10 !== 0) { ws.send(message); } else { console.log('Dropped message:', messageCount); } }); });};常见问题解决1. WebSocket 连接失败检查项:确认代理规则正确检查目标服务器是否支持 WebSocket确认防火墙设置检查 SSL 证书(对于 wss)2. 消息乱码解决方法:确认消息编码格式检查消息是否为二进制数据使用正确的解码方式3. 连接频繁断开原因:网络不稳定服务器超时设置心跳机制问题解决方法:增加超时时间实现心跳机制优化网络环境最佳实践使用插件进行复杂处理插件提供更强大的功能便于复用和维护记录消息日志便于问题排查分析消息模式测试异常场景测试网络中断测试消息丢失测试连接超时性能优化减少不必要的消息处理使用消息压缩优化消息格式
阅读 0·2月21日 16:27

whistle 在实际开发中有哪些应用场景和实战技巧?

答案Whistle 在实际开发中有许多实用的应用场景,可以大大提高开发效率和问题排查能力。常见应用场景1. 本地开发调试场景描述:前端开发时需要调用后端接口,但后端服务在本地运行,需要将线上域名指向本地服务。解决方案:# 将线上域名指向本地服务www.example.com host 127.0.0.1:3000api.example.com host 127.0.0.1:3001# 或者使用 forward 操作符www.example.com forward http://127.0.0.1:3000优点:无需修改代码中的域名快速切换本地和线上环境便于前后端联调2. 解决跨域问题场景描述:前端开发时遇到跨域问题,需要添加 CORS 响应头。解决方案:# 添加 CORS 响应头www.example.com resHeaders://{cors-headers.json}cors-headers.json:{ "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS", "Access-Control-Allow-Headers": "Content-Type, Authorization"}优点:无需后端修改代码快速解决跨域问题适合开发环境使用3. 接口数据模拟场景描述:后端接口尚未开发完成,前端需要先开发功能,需要模拟接口返回数据。解决方案:# 模拟用户接口www.example.com/api/user resBody://{mock-user.json}# 模拟列表接口www.example.com/api/list resBody://{mock-list.json}# 使用脚本动态生成数据www.example.com/api/dynamic resScript://{dynamic-mock.js}mock-user.json:{ "code": 0, "data": { "id": 1, "name": "张三", "age": 25 }}优点:前后端并行开发提高开发效率便于测试各种场景4. 多环境切换场景描述:需要在开发、测试、生产环境之间快速切换,测试不同环境的功能。解决方案:创建不同环境的配置文件:rules-dev:www.example.com host 127.0.0.1:3000api.example.com host 127.0.0.1:3001rules-test:www.example.com host test.example.comapi.example.com host api-test.example.comrules-prod:www.example.com host prod.example.comapi.example.com host api-prod.example.com切换环境:# 切换到开发环境w2 restart -f rules-dev# 切换到测试环境w2 restart -f rules-test# 切换到生产环境w2 restart -f rules-prod优点:快速切换环境避免修改代码提高测试效率5. 性能优化测试场景描述:需要测试网站性能,找出性能瓶颈。解决方案:# 启用 gzip 压缩www.example.com resHeaders://{compression-headers.json}# 设置缓存策略www.example.com/static/* resHeaders://{cache-headers.json}# 模拟慢速网络www.example.com resScript://{slow-network.js}slow-network.js:module.exports = function(req, res) { setTimeout(() => { res.end(JSON.stringify({ code: 0, data: 'success' })); }, 2000); // 延迟2秒};优点:模拟真实网络环境发现性能问题优化用户体验6. 移动端调试场景描述:需要在移动设备上调试 Web 应用或混合应用。解决方案:配置手机代理手机和电脑连接同一 Wi-Fi配置手机代理指向电脑 IP 和 whistle 端口安装 HTTPS 证书添加移动端专用规则# 移动端接口模拟m.example.com/api/user resBody://{mobile-mock-user.json}# 移动端跨域处理m.example.com resHeaders://{cors-headers.json}优点:真实设备测试捕获移动端网络请求解决移动端特定问题7. 接口错误模拟场景描述:需要测试应用对各种错误情况的处理,如网络错误、服务器错误等。解决方案:# 模拟 500 错误www.example.com/api/error resBody://{"code":500,"message":"服务器错误"}# 模拟超时www.example.com/api/timeout resScript://{timeout.js}# 模拟网络错误www.example.com/api/network-error resScript://{network-error.js}timeout.js:module.exports = function(req, res) { // 不返回响应,模拟超时 setTimeout(() => { // 可选:返回超时错误 res.statusCode = 408; res.end(JSON.stringify({ code: 408, message: '请求超时' })); }, 30000);};优点:测试异常处理逻辑提高应用健壮性便于排查问题8. 接口数据修改场景描述:需要修改接口返回的数据,测试不同数据场景。解决方案:# 修改响应数据www.example.com/api/user resScript://{modify-data.js}# 替换响应内容www.example.com resReplace://old-string/new-stringmodify-data.js:module.exports = function(req, res) { const originalEnd = res.end; res.end = function(chunk, encoding) { if (chunk) { const body = chunk.toString(); const jsonData = JSON.parse(body); // 修改数据 jsonData.data.status = 'active'; jsonData.data.timestamp = Date.now(); originalEnd.call(res, JSON.stringify(jsonData), encoding); } else { originalEnd.call(res, chunk, encoding); } };};优点:快速测试不同数据场景无需后端修改提高测试效率9. 接口请求修改场景描述:需要修改请求参数或请求头,测试不同请求场景。解决方案:# 修改请求头www.example.com reqHeaders://{custom-headers.json}# 使用脚本修改请求www.example.com reqScript://{modify-request.js}custom-headers.json:{ "X-Custom-Header": "Custom Value", "X-Request-ID": "12345"}modify-request.js:module.exports = function(req, res) { // 添加请求参数 if (req.url.includes('/api/user')) { const separator = req.url.includes('?') ? '&' : '?'; req.url += separator + 'debug=true'; } // 修改请求头 req.headers['X-Debug-Mode'] = 'true';};优点:测试不同请求场景添加调试信息便于问题排查10. WebSocket 调试场景描述:需要调试 WebSocket 连接和消息。解决方案:# WebSocket 代理ws.example.com host 127.0.0.1:8080# 使用插件调试 WebSocketws.example.com plugin://websocket-debugger优点:捕获 WebSocket 消息调试实时通信解决连接问题实战技巧1. 规则分组管理使用注释和分组来管理大量规则:# ==================== 本地开发 ====================www.local.com host 127.0.0.1:3000api.local.com host 127.0.0.1:3001# ==================== 测试环境 ====================www.test.com host test.example.comapi.test.com host api-test.example.com# ==================== 数据模拟 ====================www.example.com/api/user resBody://{mock-user.json}www.example.com/api/list resBody://{mock-list.json}2. 快速启用/禁用规则在规则前添加 # 来快速禁用规则:# www.example.com host 127.0.0.1:3000 # 禁用www.example.com host test.example.com # 启用3. 使用 Values 文件创建 Values 文件存储常用配置:values.json:{ "local-ip": "127.0.0.1", "local-port": "3000", "test-host": "test.example.com"}在规则中使用:www.example.com host {{local-ip}}:{{local-port}}4. 导出和导入配置定期导出配置文件,便于备份和分享:# 导出配置cp ~/.whistle/rules ~/backup/whistle-rules-$(date +%Y%m%d)# 导入配置cp ~/backup/whistle-rules-20240101 ~/.whistle/rules最佳实践定期备份配置避免配置丢失便于回滚使用版本控制使用 Git 管理配置文件便于团队协作添加清晰注释说明规则用途便于维护定期清理规则删除不再使用的规则保持配置简洁安全考虑不要在公共网络使用调试完成后关闭代理保护证书安全
阅读 0·2月21日 16:27

whistle 常见问题有哪些,如何排查和解决?

答案Whistle 在实际使用中可能会遇到各种问题,了解常见问题及其解决方法可以提高工作效率。安装和启动问题1. 安装失败问题:npm install -g whistle# 报错:EACCES: permission denied解决方法:方法一:使用 sudo(Mac/Linux)sudo npm install -g whistle方法二:修改 npm 目录权限sudo chown -R $(whoami) ~/.npmsudo chown -R $(whoami) /usr/local/lib/node_modules方法三:使用 nvmnvm install nodenvm use nodenpm install -g whistle2. 启动失败问题:w2 start# 报错:Port 8899 is already in use解决方法:方法一:查找并关闭占用端口的进程# Mac/Linuxlsof -i :8899kill -9 <PID># Windowsnetstat -ano | findstr :8899taskkill /PID <PID> /F方法二:使用其他端口w2 start -p 8080方法三:停止之前的 whistle 实例w2 stopw2 start3. 启动后无法访问问题:启动成功但无法访问 http://127.0.0.1:8899/解决方法:检查 whistle 是否正在运行:w2 status检查防火墙设置:Windows:允许 whistle 通过防火墙Mac:系统偏好设置 → 安全性与隐私 → 防火墙Linux:检查 iptables 或 ufw 设置检查端口是否正确:# 查看监听端口netstat -an | grep 8899配置问题1. 规则不生效问题:配置了规则但没有生效解决方法:检查规则语法:确保规则格式正确检查是否有语法错误查看规则是否被注释检查规则优先级:更具体的规则应该放在前面检查是否有规则冲突重启 whistle:w2 restart清除浏览器缓存:清除浏览器缓存和 Cookie使用隐私模式测试2. HTTPS 拦截失败问题:无法拦截 HTTPS 请求解决方法:检查 HTTPS 拦截是否启用:访问 http://127.0.0.1:8899/点击 "HTTPS" 标签勾选 "Capture HTTPS"检查证书是否正确安装:下载根证书安装到受信任的根证书颁发机构重启浏览器使用规则启用 HTTPS:pattern whistle.https://3. 代理配置错误问题:浏览器无法通过 whistle 代理访问网络解决方法:检查代理配置:确认代理地址正确:127.0.0.1:8899确认代理类型:HTTP 代理确认没有配置 PAC 文件测试代理连接:curl -x http://127.0.0.1:8899 http://www.example.com检查网络连接:确认电脑可以访问网络检查 DNS 设置性能问题1. whistle 运行缓慢问题:whistle 响应缓慢,影响开发效率解决方法:清除缓存:w2 clean cache减少规则数量:删除不必要的规则使用更精确的匹配模式增加内存限制:node --max-old-space-size=4096 $(which w2) start升级到最新版本:npm update -g whistle2. 内存占用过高问题:whistle 占用大量内存解决方法:查看内存使用:w2 memory限制日志大小:w2 log clear定期重启 whistle:w2 restart优化规则:避免使用复杂的正则表达式减少脚本处理3. CPU 占用过高问题:whistle 占用大量 CPU解决方法:查看 CPU 使用:w2 cpu检查插件:禁用不必要的插件更新插件到最新版本优化脚本:减少脚本中的复杂计算使用异步操作移动端问题1. 手机无法连接到代理问题:配置了手机代理但无法连接解决方法:检查网络连接:确认手机和电脑在同一 Wi-Fi测试手机能否访问电脑 IP检查代理配置:确认代理地址是电脑 IP确认代理端口是 8899确认代理类型是 HTTP检查防火墙:允许 whistle 通过防火墙允许 8899 端口入站连接2. HTTPS 证书安装失败问题:手机无法安装或信任 HTTPS 证书解决方法:iOS 设备:下载证书后打开"设置" → "已下载描述文件"安装证书进入"设置" → "通用" → "关于本机" → "证书信任设置"启用"完全信任"Android 设备:下载证书后打开按照提示安装进入"设置" → "安全" → "加密与凭据" → "受信任的凭据"确认证书已安装重启手机浏览器3. 某些应用无法拦截问题:某些应用的请求无法被 whistle 拦截解决方法:检查应用是否使用系统代理:某些应用不使用系统代理需要使用 VPN 模式检查证书绑定:某些应用使用证书绑定需要使用 Frida 等工具检查网络库:某些应用使用自定义网络库需要逆向分析WebSocket 问题1. WebSocket 连接失败问题:WebSocket 无法建立连接解决方法:检查代理规则:ws://example.com host 127.0.0.1:8080检查服务器支持:确认服务器支持 WebSocket检查 WebSocket 端口是否开放检查防火墙:允许 WebSocket 端口检查代理设置2. WebSocket 消息丢失问题:WebSocket 消息部分丢失解决方法:检查网络稳定性:使用稳定的网络避免频繁切换网络检查服务器负载:服务器可能过载增加服务器资源检查心跳机制:实现心跳检测自动重连机制插件问题1. 插件安装失败问题:无法安装 whistle 插件解决方法:检查 npm 源:npm config get registry# 如果不是官方源,切换到官方源npm config set registry https://registry.npmjs.org/检查网络连接:确保可以访问 npm 仓库使用代理或镜像使用淘宝镜像:npm config set registry https://registry.npmmirror.com/2. 插件运行错误问题:插件安装后运行报错解决方法:查看错误日志:w2 log检查插件版本:确认插件版本与 whistle 版本兼容更新插件到最新版本检查插件依赖:安装插件依赖npm install数据问题1. 配置丢失问题:whistle 配置意外丢失解决方法:恢复备份:cp ~/.whistle/rules.backup ~/.whistle/rules从 Git 恢复:git checkout ~/.whistle/rules重新配置:重新添加规则重新安装插件2. 日志过大问题:whistle 日志文件过大解决方法:清空日志:w2 log clear设置日志轮转:w2 log rotate定期清理:# 创建定时任务清理日志crontab -e# 添加:0 0 * * * w2 log clear最佳实践定期备份配置使用 Git 管理配置定期导出配置文件保留历史版本保持更新定期更新 whistle更新插件到最新版本关注官方公告监控资源使用定期检查内存和 CPU及时清理缓存优化规则和脚本文档化配置添加规则注释编写配置文档记录问题解决方案使用脚本自动化自动化常用操作减少手动操作提高工作效率
阅读 0·2月21日 16:27

whistle 和 Charles 有什么区别,如何选择使用?

答案Whistle 和 Charles 都是常用的网络调试代理工具,但它们在设计理念、功能特性和使用场景上有所不同。核心差异对比| 特性 | Whistle | Charles ||------|---------|---------|| 开源性质 | 完全开源免费 | 商业软件(有免费版) || 开发语言 | Node.js | Java || 配置方式 | 规则配置,更灵活 | 图形界面,更直观 || 插件系统 | 支持插件扩展 | 支持扩展 || 跨平台 | 完美支持 Windows/Mac/Linux | 主要支持 Windows/Mac || 学习曲线 | 需要学习规则语法 | 图形界面易上手 |Whistle 的优势规则配置更灵活支持复杂的规则组合可以通过脚本实现自定义逻辑规则可以版本控制开源免费无需付费即可使用全部功能社区活跃,问题解决快可以根据需求修改源码更适合团队协作规则配置可以共享支持配置文件导入导出适合集成到开发流程中性能更好基于 Node.js,启动速度快内存占用相对较小处理大量请求时更稳定Charles 的优势图形界面更友好可视化操作,无需记忆命令适合不熟悉命令行的用户界面美观,操作直观功能更全面内置更多调试工具支持更多协议提供更详细的请求分析适合快速调试启动即可使用界面操作快速适合临时调试任务选择建议选择 Whistle 的场景:需要长期使用网络代理团队协作开发需要自定义复杂的代理逻辑预算有限,需要免费工具熟悉命令行和脚本选择 Charles 的场景:偶尔需要调试网络请求更喜欢图形界面操作需要快速上手使用对可视化分析有更高要求预算充足,愿意付费总结Whistle 更适合专业开发者和技术团队,特别是需要长期、深度使用网络代理的场景。Charles 更适合偶尔使用或偏好图形界面的用户。两者都是优秀的工具,选择哪个主要取决于个人习惯和具体需求。
阅读 0·2月21日 16:27

如何开发 whistle 插件,插件的基本结构是什么?

答案Whistle 支持插件系统,可以通过开发插件来扩展其功能,实现自定义的网络请求处理逻辑。插件开发基础1. 创建插件项目mkdir whistle-plugin-democd whistle-plugin-demonpm init -y2. 创建插件入口文件创建 index.js 文件:module.exports = function(server, options) { // 插件初始化逻辑 console.log('Whistle plugin demo loaded'); // 监听请求事件 server.on('request', function(req, res) { // 处理请求 if (req.url === '/api/plugin-demo') { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ message: 'Hello from whistle plugin', timestamp: Date.now() })); } }); // 监听响应事件 server.on('response', function(req, res) { // 处理响应 console.log('Response:', req.url, res.statusCode); });};3. 配置 package.json{ "name": "whistle-plugin-demo", "version": "1.0.0", "description": "A demo whistle plugin", "main": "index.js", "whistleConfig": { "name": "demo", "description": "Demo plugin for whistle" }}插件功能实现1. 请求拦截和修改module.exports = function(server, options) { server.on('request', function(req, res) { // 修改请求头 req.headers['X-Custom-Header'] = 'Custom Value'; // 记录请求信息 console.log('Request URL:', req.url); console.log('Request Method:', req.method); console.log('Request Headers:', req.headers); });};2. 响应拦截和修改module.exports = function(server, options) { server.on('response', function(req, res) { // 修改响应头 res.setHeader('X-Response-Header', 'Custom Response'); // 修改响应体 const originalEnd = res.end; res.end = function(chunk, encoding) { if (chunk) { const body = chunk.toString(); const modifiedBody = body.replace(/old/g, 'new'); originalEnd.call(res, modifiedBody, encoding); } else { originalEnd.call(res, chunk, encoding); } }; });};3. 中间件模式module.exports = function(server, options) { // 使用 Express 风格的中间件 server.use(function(req, res, next) { console.log('Middleware:', req.url); next(); }); // 路由处理 server.get('/api/test', function(req, res) { res.json({ success: true }); });};插件配置选项module.exports = function(server, options) { // 获取插件配置 const customConfig = options.customConfig || {}; const port = options.port || 3000; console.log('Plugin options:', options);};安装和使用插件1. 本地安装插件cd whistle-plugin-demonpm linkw2 install demo2. 全局安装插件npm install -g whistle-plugin-demow2 install demo3. 在规则中使用插件www.example.com plugin://demo高级功能1. WebSocket 支持module.exports = function(server, options) { server.on('upgrade', function(req, socket, head) { // 处理 WebSocket 升级请求 console.log('WebSocket upgrade:', req.url); });};2. 文件系统操作const fs = require('fs');const path = require('path');module.exports = function(server, options) { server.on('request', function(req, res) { if (req.url === '/api/file') { const filePath = path.join(__dirname, 'data.json'); const data = fs.readFileSync(filePath, 'utf8'); res.end(data); } });};3. 数据库集成const mysql = require('mysql');module.exports = function(server, options) { const connection = mysql.createConnection({ host: 'localhost', user: 'root', password: 'password', database: 'test' }); server.on('request', function(req, res) { if (req.url === '/api/users') { connection.query('SELECT * FROM users', function(error, results) { if (error) { res.statusCode = 500; res.end(JSON.stringify({ error: error.message })); } else { res.end(JSON.stringify(results)); } }); } });};最佳实践错误处理添加适当的错误处理逻辑记录错误日志提供友好的错误信息性能优化避免阻塞操作使用缓存减少重复计算合理使用异步操作安全性验证输入参数防止注入攻击敏感信息加密存储文档和测试编写清晰的使用文档添加单元测试提供示例代码
阅读 0·2月21日 16:26

whistle 支持哪些协议,如何处理不同协议的代理?

答案Whistle 支持多种协议的代理,包括 HTTP、HTTPS、WebSocket、HTTP/2 等,可以满足不同场景的调试需求。支持的协议1. HTTP 协议基本代理:www.example.com host 127.0.0.1:8080转发代理:www.example.com forward http://127.0.0.1:8080修改请求:www.example.com reqHeaders://{custom-headers.json}2. HTTPS 协议基本代理:www.example.com host 127.0.0.1:8443启用 HTTPS 拦截:pattern whistle.https://配置 HTTPS 证书:下载根证书安装到系统启用 HTTPS 拦截3. WebSocket 协议基本代理:ws://example.com host 127.0.0.1:8080wss://example.com host 127.0.0.1:8080转发代理:ws://example.com forward ws://127.0.0.1:8080wss://example.com forward wss://127.0.0.1:8080WebSocket 消息捕获:自动捕获连接建立记录发送和接收的消息显示连接状态4. HTTP/2 协议Whistle 支持 HTTP/2 协议的代理:自动降级到 HTTP/1.1支持 HTTP/2 的多路复用支持服务器推送5. SOCKS 代理配置 SOCKS 代理:www.example.com socks://127.0.0.1:1080SOCKS5 代理:www.example.com socks5://127.0.0.1:1080协议转换1. HTTP 转 HTTPS配置规则:http://www.example.com forward https://www.example.com2. HTTPS 转 HTTP配置规则:https://www.example.com forward http://www.example.com3. WebSocket 转 HTTP配置规则:ws://example.com forward http://127.0.0.1:8080协议特定配置1. HTTP 协议配置设置请求方法:www.example.com method://POST设置请求头:www.example.com reqHeaders://{http-headers.json}设置响应头:www.example.com resHeaders://{http-headers.json}2. HTTPS 协议配置禁用 SSL 验证:www.example.com disable://ssl设置 SSL 版本:www.example.com ssl://TLSv1.2自定义 CA 证书:www.example.com ca://{custom-ca.crt}3. WebSocket 协议配置设置 WebSocket 子协议:ws://example.com protocol://chat设置 WebSocket 超时:ws://example.com timeout://30000设置 WebSocket 心跳:ws://example.com ping://30000多协议场景1. 混合协议代理同时代理 HTTP 和 HTTPS:www.example.com host 127.0.0.1:8080api.example.com host 127.0.0.1:8080同时代理 WebSocket 和 HTTP:ws://example.com host 127.0.0.1:8080www.example.com host 127.0.0.1:80802. 协议路由根据协议路由:# HTTP 路由到本地http://www.example.com host 127.0.0.1:8080# HTTPS 路由到测试服务器https://www.example.com host test.example.com# WebSocket 路由到本地ws://www.example.com host 127.0.0.1:80803. 协议转换场景开发环境使用 HTTP,生产环境使用 HTTPS:# 开发环境www.example.com forward http://127.0.0.1:3000# 生产环境www.example.com forward https://api.example.com协议调试技巧1. 查看协议信息在 whistle 管理界面中:点击 "Network" 标签点击请求查看详情查看 "General" 标签中的协议信息2. 协议降级测试测试 HTTP/2 降级:www.example.com disable://h2测试 WebSocket 降级:ws://example.com disable://websocket3. 协议性能测试测试不同协议的性能:# HTTP/1.1www.example.com disable://h2# HTTP/2www.example.com enable://h2协议安全1. HTTPS 安全启用 HTTPS 拦截:pattern whistle.https://验证证书:www.example.com verify://ssl禁用不安全的协议:www.example.com disable://ssl3www.example.com disable://tls12. WebSocket 安全使用 WSS:wss://example.com host 127.0.0.1:8080验证 WebSocket 握手:ws://example.com verify://websocket协议兼容性1. 浏览器兼容性Chrome/Edge:完全支持所有协议Firefox:支持 HTTP、HTTPS、WebSocketSafari:支持 HTTP、HTTPS、WebSocket2. 服务器兼容性Nginx:支持 HTTP、HTTPS、WebSocketApache:支持 HTTP、HTTPSNode.js:支持所有协议3. 移动端兼容性iOS:支持 HTTP、HTTPS、WebSocketAndroid:支持 HTTP、HTTPS、WebSocket协议最佳实践1. 开发环境使用 HTTP 协议便于调试使用 WebSocket 实时通信禁用 SSL 验证加快速度2. 测试环境使用 HTTPS 模拟生产环境使用 WSS 测试安全连接启用 SSL 验证确保安全3. 生产环境使用 HTTPS 确保安全使用 WSS 保护 WebSocket启用所有安全验证协议故障排查1. HTTPS 连接失败检查项:证书是否正确安装SSL 版本是否匹配防火墙是否阻止解决方法:www.example.com disable://ssl2. WebSocket 连接失败检查项:代理规则是否正确服务器是否支持 WebSocket网络是否稳定解决方法:ws://example.com forward ws://127.0.0.1:80803. 协议不兼容检查项:客户端和服务器协议版本浏览器支持情况服务器配置解决方法:www.example.com disable://h2
阅读 0·2月21日 16:26

whistle 如何与其他开发工具集成,有哪些集成方案?

答案Whistle 支持与其他开发工具集成,可以构建完整的开发和调试工作流。与浏览器集成1. Chrome DevTools 集成使用 Chrome DevTools 调试:配置浏览器代理指向 whistle打开 Chrome DevTools查看 Network 标签whistle 捕获的请求会显示在 DevTools 中优势:结合 Chrome DevTools 的强大功能查看详细的请求和响应信息使用 Chrome 的性能分析工具2. Firefox Developer Tools 集成配置 Firefox 代理:打开 Firefox 设置配置代理指向 whistle打开 Developer Tools查看 Network Monitor优势:Firefox 的网络监控功能查看 WebSocket 连接分析网络性能3. Safari Web Inspector 集成配置 Safari 代理:打开 Safari 偏好设置配置代理指向 whistle启用开发菜单打开 Web Inspector优势:适合 iOS 开发查看 iOS 设备的网络请求调试 Safari 特定问题与编辑器集成1. VS Code 集成安装 whistle 插件:code --install-extension whistle-for-vscode使用 VS Code 编辑规则:打开 whistle 配置文件使用 VS Code 编辑规则保存后自动生效优势:语法高亮自动补全错误提示2. WebStorm 集成配置 WebStorm:打开 Settings配置 HTTP Proxy指向 whistle 代理地址优势:内置的 HTTP 客户端直接测试 API查看请求响应3. Vim/Neovim 集成使用 Vim 编辑规则:" 配置语法高亮autocmd BufRead,BufNewFile *.rules set filetype=whistle优势:快速编辑自定义配置键盘操作与构建工具集成1. Webpack 集成配置 Webpack 代理:// webpack.config.jsmodule.exports = { devServer: { proxy: { '/api': { target: 'http://127.0.0.1:8899', changeOrigin: true } } }};优势:开发服务器自动代理热重载时保持代理统一的开发环境2. Vite 集成配置 Vite 代理:// vite.config.jsexport default { server: { proxy: { '/api': { target: 'http://127.0.0.1:8899', changeOrigin: true } } }};优势:快速的开发服务器原生 ES 模块支持更好的热更新3. Create React App 集成配置代理:// package.json{ "proxy": "http://127.0.0.1:8899"}优势:零配置代理适合 React 项目自动处理跨域与测试工具集成1. Jest 集成配置 Jest 测试:// jest.config.jsmodule.exports = { setupFilesAfterEnv: ['<rootDir>/setup-whistle.js']};setup-whistle.js:// 配置 whistle 用于测试const { setupWhistle } = require('jest-whistle');setupWhistle({ rules: { 'api.example.com': 'host 127.0.0.1:3000' }});优势:测试时使用真实代理模拟网络请求集成测试环境2. Cypress 集成配置 Cypress:// cypress.config.jsmodule.exports = { e2e: { setupNodeEvents(on, config) { on('before:browser:launch', (browser, launchOptions) => { // 配置浏览器代理 launchOptions.args.push(`--proxy-server=http://127.0.0.1:8899`); }); } }};优势:E2E 测试时使用代理捕获测试请求调试测试问题3. Playwright 集成配置 Playwright:// playwright.config.jsmodule.exports = { use: { proxy: { server: 'http://127.0.0.1:8899' } }};优势:跨浏览器测试自动化代理配置网络请求拦截与 CI/CD 集成1. GitHub Actions 集成配置 GitHub Actions:name: CIon: [push]jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Setup Node.js uses: actions/setup-node@v2 with: node-version: '16' - name: Install whistle run: npm install -g whistle - name: Start whistle run: w2 start - name: Run tests run: npm test - name: Stop whistle run: w2 stop优势:自动化测试持续集成统一测试环境2. Jenkins 集成配置 Jenkins Pipeline:pipeline { agent any stages { stage('Setup') { steps { sh 'npm install -g whistle' sh 'w2 start' } } stage('Test') { steps { sh 'npm test' } } stage('Cleanup') { steps { sh 'w2 stop' } } }}优势:灵活的流水线自定义测试步骤集成其他工具3. GitLab CI 集成配置 GitLab CI:stages: - testtest: stage: test script: - npm install -g whistle - w2 start - npm test - w2 stop优势:内置 CI/CD简单配置自动化部署与监控工具集成1. Sentry 集成配置 Sentry:const Sentry = require('@sentry/node');Sentry.init({ dsn: 'your-dsn', beforeSend(event) { // 添加 whistle 请求信息 event.request = { ...event.request, headers: { 'X-Whistle-Request': 'true' } }; return event; }});优势:错误追踪请求上下文性能监控2. New Relic 集成配置 New Relic:const newrelic = require('newrelic');// 添加 whistle 请求信息newrelic.setTransactionName('whistle-request');优势:应用性能监控请求追踪错误分析3. Datadog 集成配置 Datadog:const tracer = require('dd-trace').init();// 追踪 whistle 请求tracer.trace('whistle-request', () => { // 请求处理逻辑});优势:分布式追踪性能分析实时监控与文档工具集成1. Swagger/OpenAPI 集成生成 whistle 规则:const swaggerParser = require('swagger-parser');const fs = require('fs');swaggerParser.parse('swagger.json') .then(api => { const rules = []; Object.keys(api.paths).forEach(path => { const fullPath = api.host + path; rules.push(`${fullPath} host 127.0.0.1:3000`); }); fs.writeFileSync('whistle-rules.txt', rules.join('\n')); });优势:自动生成规则API 文档同步接口测试2. Postman 集成导出 Postman 集合:在 Postman 中配置代理导出集合为 JSON转换为 whistle 规则优势:API 测试集合管理团队协作3. GraphQL 集成配置 GraphQL 代理:graphql.example.com host 127.0.0.1:4000graphql.example.com reqHeaders://{graphql-headers.json}优势:GraphQL 调试查询优化Schema 验证最佳实践选择合适的集成方式根据项目需求选择考虑团队技术栈评估维护成本保持配置简洁避免过度集成定期清理配置文档化集成方案自动化集成流程使用脚本自动化集成到 CI/CD定期测试集成监控集成效果跟踪性能指标收集使用反馈持续优化集成
阅读 0·2月21日 16:26

whistle 如何实现数据模拟,有哪些常用的模拟方法?

答案Whistle 提供了强大的数据模拟功能,可以在前端开发中模拟接口返回数据,提高开发效率。数据模拟方法1. 使用 resBody 操作符直接指定模拟数据:www.example.com/api/user resBody://{"code":0,"data":{"name":"张三","age":25}}2. 使用 Values 文件创建 Values 文件存储模拟数据:创建文件:mock-user.json{ "code": 0, "data": { "id": 1, "name": "张三", "age": 25, "email": "zhangsan@example.com" }}配置规则:www.example.com/api/user resBody://{mock-user.json}3. 使用 resScript 动态生成数据创建脚本文件动态生成响应:创建文件:mock-user.jsmodule.exports = function(req, res) { const userId = req.query.id || 1; res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify({ code: 0, data: { id: userId, name: `用户${userId}`, timestamp: Date.now() } }));};配置规则:www.example.com/api/user resScript://{mock-user.js}4. 使用 whistle 插件开发 whistle 插件实现更复杂的模拟逻辑:module.exports = function(server, options) { server.on('request', function(req, res) { if (req.url === '/api/mock') { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ mock: true })); } });};高级模拟技巧1. 延迟响应www.example.com/api/* resScript://{delay-response.js}delay-response.js:module.exports = function(req, res) { setTimeout(() => { res.end(JSON.stringify({ code: 0, data: 'success' })); }, 2000); // 延迟2秒};2. 错误模拟www.example.com/api/error resBody://{"code":500,"message":"服务器错误"}3. 条件模拟根据请求参数返回不同数据:module.exports = function(req, res) { const type = req.query.type; let data; if (type === 'success') { data = { code: 0, message: '成功' }; } else if (type === 'error') { data = { code: 500, message: '失败' }; } else { data = { code: 400, message: '参数错误' }; } res.end(JSON.stringify(data));};最佳实践使用 Values 文件管理静态数据使用 resScript 处理动态数据按功能模块组织模拟数据添加注释说明模拟数据的用途定期清理不再使用的模拟规则
阅读 0·2月21日 16:26

whistle 的 Values 功能是什么,如何使用和管理 Values?

答案Whistle 提供了强大的 Values 功能,可以存储和管理各种配置数据,在规则中灵活使用。Values 基础1. 什么是 ValuesValues 是 whistle 提供的一种数据存储机制,可以存储:配置数据模拟数据常量值环境变量2. Values 文件格式Values 文件支持多种格式:JSON 格式:values.jsonProperties 格式:values.propertiesINI 格式:values.iniYAML 格式:values.yaml创建和使用 Values1. 创建 JSON 格式的 Values创建文件:values.json{ "local-host": "127.0.0.1", "local-port": "3000", "test-host": "test.example.com", "test-port": "8080", "api-base": "https://api.example.com", "timeout": "5000", "retry-count": "3"}在规则中使用:www.example.com host {{local-host}}:{{local-port}}api.example.com forward {{api-base}}2. 创建 Properties 格式的 Values创建文件:values.propertieslocal.host=127.0.0.1local.port=3000test.host=test.example.comtest.port=8080api.base=https://api.example.comtimeout=5000retry.count=3在规则中使用:www.example.com host {{local.host}}:{{local.port}}api.example.com forward {{api.base}}3. 创建 INI 格式的 Values创建文件:values.ini[local]host=127.0.0.1port=3000[test]host=test.example.comport=8080[api]base=https://api.example.comtimeout=5000retry=3在规则中使用:www.example.com host {{local.host}}:{{local.port}}api.example.com forward {{api.base}}Values 高级用法1. 嵌套对象创建嵌套的 Values:{ "servers": { "local": { "host": "127.0.0.1", "port": "3000" }, "test": { "host": "test.example.com", "port": "8080" } }, "api": { "base": "https://api.example.com", "version": "v1" }}在规则中使用:www.example.com host {{servers.local.host}}:{{servers.local.port}}api.example.com forward {{api.base}}/{{api.version}}2. 数组数据创建包含数组的 Values:{ "allowed-origins": [ "https://www.example.com", "https://test.example.com", "https://localhost:3000" ], "api-endpoints": [ "/api/user", "/api/list", "/api/detail" ]}在规则中使用:# 使用数组的第一个元素www.example.com resHeaders://{cors-{{allowed-origins.0}}.json}3. 环境变量创建环境变量 Values:{ "env": "development", "api-url": "https://dev-api.example.com", "debug": true}在规则中使用:# 根据环境变量配置www.example.com forward {{api-url}}www.example.com reqHeaders://{debug-{{debug}}.json}Values 在脚本中的使用1. 在 reqScript 中使用创建脚本:use-values.jsconst values = require('./values.json');module.exports = function(req, res) { // 使用 Values 中的数据 const timeout = values.timeout || 5000; const retryCount = values['retry-count'] || 3; req.headers['X-Timeout'] = timeout; req.headers['X-Retry-Count'] = retryCount;};配置规则:www.example.com reqScript://{use-values.js}2. 在 resScript 中使用创建脚本:use-values-res.jsconst values = require('./values.json');module.exports = function(req, res) { const originalEnd = res.end; res.end = function(chunk, encoding) { if (chunk) { const body = chunk.toString(); const jsonData = JSON.parse(body); // 使用 Values 中的数据 jsonData.apiVersion = values.api.version; jsonData.environment = values.env; originalEnd.call(res, JSON.stringify(jsonData), encoding); } else { originalEnd.call(res, chunk, encoding); } };};配置规则:www.example.com resScript://{use-values-res.js}3. 在插件中使用创建插件:values-plugin.jsconst fs = require('fs');const path = require('path');module.exports = function(server, options) { // 读取 Values 文件 const valuesPath = path.join(__dirname, 'values.json'); const values = JSON.parse(fs.readFileSync(valuesPath, 'utf8')); server.on('request', function(req, res) { // 使用 Values 中的数据 req.values = values; // 根据环境变量处理请求 if (values.env === 'development') { req.headers['X-Debug'] = 'true'; } });};Values 管理技巧1. 多环境 Values创建不同环境的 Values 文件:values-dev.json:{ "env": "development", "api-url": "https://dev-api.example.com", "debug": true}values-test.json:{ "env": "testing", "api-url": "https://test-api.example.com", "debug": true}values-prod.json:{ "env": "production", "api-url": "https://api.example.com", "debug": false}切换环境:# 使用开发环境cp values-dev.json values.json# 使用测试环境cp values-test.json values.json# 使用生产环境cp values-prod.json values.json2. Values 文件组织按功能模块组织:api-values.json:{ "api-base": "https://api.example.com", "api-version": "v1", "timeout": "5000"}cors-values.json:{ "allowed-origins": [ "https://www.example.com", "https://test.example.com" ], "allowed-methods": [ "GET", "POST", "PUT", "DELETE" ]}在规则中使用:api.example.com forward {{api-values.api-base}}/{{api-values.api-version}}www.example.com resHeaders://{cors-values.json}3. Values 版本控制使用 Git 管理 Values 文件:# 初始化 Git 仓库git init# 添加 Values 文件git add values.json# 提交git commit -m "Add values configuration"# 推送到远程仓库git push origin mainValues 最佳实践1. 命名规范使用小写字母和连字符:local-host使用有意义的名称:api-base-url避免使用特殊字符2. 数据类型字符串:用引号包裹数字:直接使用布尔值:使用 true 或 false数组:使用方括号对象:使用花括号3. 注释说明在 Values 文件中添加注释:{ "local-host": "127.0.0.1", "local-port": "3000", "api-base": "https://api.example.com", "timeout": "5000"}创建配套的 README 文件:# Values 配置说明## 配置项说明- `local-host`: 本地服务器地址- `local-port`: 本地服务器端口- `api-base`: API 基础地址- `timeout`: 请求超时时间(毫秒)## 使用方法在 whistle 规则中使用 `{{key}}` 引用配置项。4. 安全考虑不要在 Values 中存储敏感信息使用环境变量管理敏感数据定期更新 Values 文件Values 实战示例1. 动态配置代理创建 Values:{ "proxy": { "enabled": true, "host": "127.0.0.1", "port": "8080" }}配置规则:{{#if proxy.enabled}}www.example.com host {{proxy.host}}:{{proxy.port}}{{/if}}2. 多域名配置创建 Values:{ "domains": { "www": "www.example.com", "api": "api.example.com", "static": "static.example.com" }, "servers": { "local": "127.0.0.1:3000", "test": "test.example.com:8080" }}配置规则:{{domains.www}} host {{servers.local}}{{domains.api}} forward https://{{servers.test}}{{domains.static}} host {{servers.local}}3. 条件配置创建 Values:{ "features": { "new-feature": true, "beta-feature": false }}配置规则:{{#if features.new-feature}}www.example.com/new-feature resBody://{new-feature.json}{{/if}}{{#if features.beta-feature}}www.example.com/beta resBody://{beta-feature.json}{{/if}}
阅读 0·2月21日 16:26

whistle 如何管理配置规则,如何进行团队协作?

答案Whistle 提供了多种方式来管理配置规则,包括通过 Web 界面、命令行和配置文件进行管理,支持团队协作和版本控制。配置规则管理方式1. Web 界面管理访问管理界面:http://127.0.0.1:8899/操作步骤:点击 "Rules" 标签在编辑器中添加或修改规则点击 "Save" 保存规则规则立即生效优点:可视化操作,直观易用实时预览规则效果适合快速调试2. 命令行管理启动 whistle:# 启动 whistlew2 start# 指定端口启动w2 start -p 8080# 指定配置文件启动w2 start -f custom.rules停止 whistle:w2 stop重启 whistle:w2 restart查看运行状态:w2 status3. 配置文件管理默认配置文件位置:Windows: C:\Users\{username}\.whistle\rulesMac/Linux: ~/.whistle/rules配置文件格式:# 注释:这是规则说明# 基本规则www.example.com host 127.0.0.1:8080# 分组规则# 本地开发www.local.com host 127.0.0.1:3000api.local.com host 127.0.0.1:3001# 测试环境www.test.com host test.example.comapi.test.com host api-test.example.com# 生产环境www.prod.com host prod.example.com规则优先级1. 匹配顺序Whistle 按照规则在配置文件中的顺序从上到下匹配,一旦匹配成功就不再继续匹配后续规则。2. 优先级规则精确匹配 > 通配符匹配 > 正则表达式匹配更具体的规则应该放在前面使用 # 注释来组织规则3. 规则示例# 精确匹配(优先级最高)www.example.com/api/user host 127.0.0.1:8080# 通配符匹配*.example.com/api/* host 127.0.0.1:8080# 正则表达式匹配(优先级最低)/^https:\/\/www\.example\.com\/api\/.*/ host 127.0.0.1:8080团队协作管理1. 配置文件版本控制使用 Git 管理配置文件:# 初始化 Git 仓库cd ~/.whistlegit init# 添加配置文件git add rules# 提交配置git commit -m "Add whistle rules"# 推送到远程仓库git remote add origin https://github.com/your-org/whistle-rules.gitgit push -u origin main2. 共享配置文件方法一:通过 Git 共享将配置文件放在 Git 仓库中团队成员克隆仓库使用符号链接到 whistle 配置目录# 克隆配置仓库git clone https://github.com/your-org/whistle-rules.git ~/whistle-config# 创建符号链接ln -s ~/whistle-config/rules ~/.whistle/rules方法二:通过配置文件导入导出导出配置文件通过团队协作工具分享其他成员导入配置3. 环境配置分离创建不同环境的配置文件:# 开发环境rules-dev:www.dev.com host 127.0.0.1:3000api.dev.com host 127.0.0.1:3001# 测试环境rules-test:www.test.com host test.example.comapi.test.com host api-test.example.com# 生产环境rules-prod:www.prod.com host prod.example.comapi.prod.com host api-prod.example.com切换环境:# 使用开发环境配置w2 start -f rules-dev# 使用测试环境配置w2 start -f rules-test# 使用生产环境配置w2 start -f rules-prod配置管理最佳实践1. 规则组织按功能分组:# 本地开发服务# ====================www.local.com host 127.0.0.1:3000api.local.com host 127.0.0.1:3001# 测试环境# ====================www.test.com host test.example.comapi.test.com host api-test.example.com# 数据模拟# ====================www.example.com/api/user resBody://{mock-user.json}www.example.com/api/list resBody://{mock-list.json}2. 注释规范添加清晰的注释:# 用户接口模拟# 用于前端开发,模拟用户数据www.example.com/api/user resBody://{mock-user.json}# 跨域处理# 解决开发环境跨域问题www.example.com resHeaders://{cors-headers.json}3. 配置备份定期备份配置:# 备份当前配置cp ~/.whistle/rules ~/.whistle/rules.backup.$(date +%Y%m%d)# 恢复配置cp ~/.whistle/rules.backup.20240101 ~/.whistle/rules4. 配置验证验证规则语法:在 Web 界面中检查规则是否高亮查看规则是否生效测试规则是否按预期工作高级配置管理1. 使用 Values 文件创建 Values 文件存储配置:创建文件:values.json{ "local-host": "127.0.0.1", "local-port": "3000", "test-host": "test.example.com", "mock-data": { "user": { "name": "张三", "age": 25 } }}在规则中使用:www.example.com host {{local-host}}:{{local-port}}2. 使用插件扩展配置开发配置管理插件:module.exports = function(server, options) { server.on('request', function(req, res) { // 根据环境变量动态配置 const env = process.env.NODE_ENV || 'development'; if (env === 'development') { req.headers['X-Environment'] = 'dev'; } else if (env === 'production') { req.headers['X-Environment'] = 'prod'; } });};3. 自动化配置使用脚本自动配置:#!/bin/bash# auto-config.sh# 获取当前环境ENV=${1:-dev}# 复制对应环境的配置文件cp ~/.whistle/rules-$ENV ~/.whistle/rules# 重启 whistlew2 restartecho "Whistle configured for $ENV environment"使用脚本:./auto-config.sh dev # 配置开发环境./auto-config.sh test # 配置测试环境./auto-config.sh prod # 配置生产环境常见问题解决1. 规则不生效检查项:确认规则语法正确检查规则优先级确认 whistle 正在运行清除浏览器缓存2. 配置冲突解决方法:使用更具体的规则调整规则顺序使用注释标记规则用途3. 配置文件损坏恢复方法:从备份恢复重新初始化配置使用版本控制恢复
阅读 0·2月21日 16:26