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

面试题手册

如何开发 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

whistle 如何捕获和查看网络请求,有哪些过滤和搜索技巧?

答案Whistle 提供了多种方式来捕获和查看网络请求,帮助开发者快速定位和解决问题。请求捕获基础1. 启动 whistle 并配置代理启动 whistle:w2 start配置浏览器代理:访问 http://127.0.0.1:8899/点击 "Proxy" 标签按照提示配置浏览器代理2. 查看请求列表在 whistle 管理界面:点击 "Network" 标签查看所有捕获的请求默认按时间顺序排列请求过滤和搜索1. 按类型过滤过滤 HTTP 请求:点击 "All" 下拉菜单选择 "XHR" 过滤 AJAX 请求选择 "Doc" 过滤文档请求选择 "CSS" 过滤样式表选择 "JS" 过滤 JavaScript 文件选择 "Img" 过滤图片选择 "Media" 过滤媒体文件选择 "WS" 过滤 WebSocket2. 按域名过滤在搜索框输入域名:example.com或者使用通配符:*.example.com3. 按状态码过滤过滤成功请求:status:200过滤错误请求:status:4xxstatus:5xx4. 按方法过滤过滤 GET 请求:method:GET过滤 POST 请求:method:POST5. 按关键词搜索搜索 URL 包含关键词的请求:api/user搜索响应内容:body:success请求详情查看1. 查看请求头点击请求后查看 "Headers" 标签:Request Headers:请求头信息Response Headers:响应头信息General:通用信息(URL、方法、状态码等)2. 查看请求体点击 "Payload" 标签:Query String Parameters:查询参数Form Data:表单数据Request Payload:请求体(JSON 等)3. 查看响应体点击 "Response" 标签:查看完整的响应内容支持格式化 JSON支持查看 HTML支持查看图片4. 查看时间信息点击 "Timing" 标签:DNS Lookup:DNS 查询时间TCP Connection:TCP 连接时间SSL Handshake:SSL 握手时间Request Sent:请求发送时间Waiting (TTFB):等待响应时间Content Download:内容下载时间Total:总时间高级捕获功能1. 捕获 HTTPS 请求启用 HTTPS 拦截:点击 "HTTPS" 标签勾选 "Capture HTTPS"下载并安装根证书或者使用规则:pattern whistle.https://2. 捕获 WebSocket 请求WebSocket 请求会自动显示在请求列表中:标记为 "WS" 类型显示连接状态记录消息历史3. 捕获移动端请求配置手机代理:手机和电脑连接同一 Wi-Fi配置手机代理指向电脑 IP 和 whistle 端口安装 HTTPS 证书查看移动端请求:请求会显示在同一个列表中可以通过 User-Agent 识别设备4. 捕获 Service Worker 请求Service Worker 的请求也会被捕获:显示请求来源标记为 Service Worker 请求可以查看缓存状态请求导出和分析1. 导出 HAR 文件导出步骤:点击 "Export" 按钮选择 "Export HAR"保存 HAR 文件HAR 文件用途:用于性能分析用于问题排查用于自动化测试2. 导出为 CSV导出步骤:点击 "Export" 按钮选择 "Export CSV"保存 CSV 文件CSV 文件用途:数据分析报表生成数据导入3. 导出为 JSON导出步骤:点击 "Export" 按钮选择 "Export JSON"保存 JSON 文件JSON 文件用途:自定义分析数据处理集成其他工具请求修改和重放1. 修改请求修改请求头:右键点击请求选择 "Edit and Resend"修改请求头点击 "Send"修改请求体:右键点击请求选择 "Edit and Resend"修改请求体点击 "Send"2. 重放请求快速重放:右键点击请求选择 "Replay"请求会重新发送批量重放:选择多个请求右键点击选择 "Replay Selected"请求监控和告警1. 实时监控启用实时监控:请求会实时显示在列表中自动滚动到最新请求显示请求计数2. 设置告警规则创建告警规则:# 状态码告警status:5xx alert:Server Error# 响应时间告警time:>3000 alert:Slow Request# 响应大小告警size:>1MB alert:Large Response3. 查看统计信息统计面板:总请求数成功请求数失败请求数平均响应时间总数据量实用技巧1. 使用快捷键Ctrl/Cmd + F:搜索请求Ctrl/Cmd + E:编辑并重发请求Ctrl/Cmd + R:重放请求Delete:删除选中请求Ctrl/Cmd + A:全选请求2. 保存过滤条件保存常用过滤条件:设置过滤条件点击 "Save Filter"输入名称保存使用保存的过滤条件:点击 "Saved Filters"选择保存的过滤条件3. 使用书签添加书签:右键点击请求选择 "Add Bookmark"输入名称保存查看书签:点击 "Bookmarks" 标签查看所有书签请求4. 使用注释添加注释:右键点击请求选择 "Add Comment"输入注释保存查看注释:注释会显示在请求列表中鼠标悬停查看完整注释最佳实践定期清理请求列表避免列表过长提高查找效率使用过滤条件快速定位按类型、域名、状态码过滤使用关键词搜索保存重要请求使用书签功能添加注释说明导出数据进行分析导出 HAR 文件用于性能分析导出 CSV/JSON 用于数据处理使用快捷键提高效率熟悉常用快捷键提高操作速度
阅读 0·2月21日 16:25

whistle 如何解决跨域问题,有哪些常见的跨域场景?

答案Whistle 提供了多种方式来处理跨域问题,可以在开发环境中快速解决 CORS 相关问题。跨域问题基础1. 什么是跨域跨域是指浏览器出于安全考虑,限制从一个域名的网页向另一个域名的资源发起请求。同源策略限制:协议不同(http vs https)域名不同(example.com vs test.com)端口不同(80 vs 8080)2. CORS 响应头解决跨域需要服务器返回正确的 CORS 响应头:Access-Control-Allow-Origin:允许的源Access-Control-Allow-Methods:允许的 HTTP 方法Access-Control-Allow-Headers:允许的请求头Access-Control-Allow-Credentials:是否允许携带凭证Access-Control-Max-Age:预检请求的缓存时间使用 whistle 解决跨域1. 添加 CORS 响应头创建 CORS 响应头文件:cors-headers.json{ "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS, PATCH", "Access-Control-Allow-Headers": "Content-Type, Authorization, X-Requested-With", "Access-Control-Allow-Credentials": "true", "Access-Control-Max-Age": "86400"}配置规则:www.example.com resHeaders://{cors-headers.json}api.example.com resHeaders://{cors-headers.json}2. 针对特定域名创建特定域名的 CORS 响应头:cors-specific.json{ "Access-Control-Allow-Origin": "https://www.myapp.com", "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS", "Access-Control-Allow-Headers": "Content-Type, Authorization", "Access-Control-Allow-Credentials": "true"}配置规则:api.example.com resHeaders://{cors-specific.json}3. 处理预检请求创建脚本:handle-preflight.jsmodule.exports = function(req, res) { // 处理 OPTIONS 预检请求 if (req.method === 'OPTIONS') { res.statusCode = 204; res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization'); res.setHeader('Access-Control-Max-Age', '86400'); res.end(); }};配置规则:api.example.com reqScript://{handle-preflight.js}高级跨域处理1. 动态设置 Allow-Origin创建脚本:dynamic-cors.jsmodule.exports = function(req, res) { const originalEnd = res.end; res.end = function(chunk, encoding) { // 动态设置允许的源 const origin = req.headers['origin']; if (origin) { res.setHeader('Access-Control-Allow-Origin', origin); res.setHeader('Access-Control-Allow-Credentials', 'true'); } originalEnd.call(res, chunk, encoding); };};配置规则:api.example.com resScript://{dynamic-cors.js}2. 根据请求路径设置不同的 CORS 策略创建脚本:path-based-cors.jsmodule.exports = function(req, res) { const originalEnd = res.end; res.end = function(chunk, encoding) { // 根据路径设置不同的 CORS 策略 if (req.url.startsWith('/api/public/')) { res.setHeader('Access-Control-Allow-Origin', '*'); } else if (req.url.startsWith('/api/private/')) { const origin = req.headers['origin']; if (origin && origin.includes('myapp.com')) { res.setHeader('Access-Control-Allow-Origin', origin); res.setHeader('Access-Control-Allow-Credentials', 'true'); } } originalEnd.call(res, chunk, encoding); };};配置规则:api.example.com resScript://{path-based-cors.js}3. 代理到同源使用 forward 操作符:api.example.com forward http://127.0.0.1:3000或者使用 host 操作符:api.example.com host 127.0.0.1:3000常见跨域场景1. 前端开发本地调试场景:前端在 localhost:3000,后端在 api.example.com解决方案:# 添加 CORS 响应头api.example.com resHeaders://{cors-headers.json}# 或者将后端代理到本地api.example.com host 127.0.0.1:80802. 多个子域名之间通信场景:www.example.com 需要访问 api.example.com解决方案:# 允许特定子域名api.example.com resHeaders://{cors-subdomain.json}cors-subdomain.json:{ "Access-Control-Allow-Origin": "https://www.example.com", "Access-Control-Allow-Credentials": "true"}3. 携带凭证的请求场景:需要携带 Cookie 或 Authorization 头的请求解决方案:api.example.com resHeaders://{cors-with-credentials.json}cors-with-credentials.json:{ "Access-Control-Allow-Origin": "https://www.myapp.com", "Access-Control-Allow-Credentials": "true", "Access-Control-Allow-Headers": "Content-Type, Authorization"}跨域调试技巧1. 查看预检请求在 whistle 管理界面中:点击 "Network" 标签筛选 "OPTIONS" 方法的请求查看请求和响应头检查 CORS 响应头是否正确2. 验证 CORS 配置创建验证脚本:verify-cors.jsmodule.exports = function(req, res) { console.log('Request Origin:', req.headers['origin']); console.log('Request Method:', req.method); console.log('Request Headers:', req.headers['access-control-request-headers']); const originalEnd = res.end; res.end = function(chunk, encoding) { console.log('Response CORS Headers:'); console.log(' Access-Control-Allow-Origin:', res.getHeader('Access-Control-Allow-Origin')); console.log(' Access-Control-Allow-Methods:', res.getHeader('Access-Control-Allow-Methods')); console.log(' Access-Control-Allow-Headers:', res.getHeader('Access-Control-Allow-Headers')); originalEnd.call(res, chunk, encoding); };};配置规则:api.example.com resScript://{verify-cors.js}3. 模拟不同的源创建脚本:simulate-origin.jsmodule.exports = function(req, res) { // 模拟不同的请求源 const origins = [ 'https://www.example.com', 'https://test.example.com', 'https://localhost:3000' ]; // 随机选择一个源 const randomOrigin = origins[Math.floor(Math.random() * origins.length)]; req.headers['origin'] = randomOrigin; console.log('Simulated Origin:', randomOrigin);};配置规则:api.example.com reqScript://{simulate-origin.js}最佳实践开发环境使用宽松的 CORS 策略允许所有源:*方便开发和测试生产环境使用严格的 CORS 策略只允许特定的源启用凭证验证定期检查 CORS 配置确保响应头正确避免安全漏洞使用环境变量管理 CORS 配置开发环境:宽松策略生产环境:严格策略文档化 CORS 策略记录允许的源说明特殊处理逻辑
阅读 0·2月21日 16:25

whistle 如何进行性能监控和分析,有哪些优化建议?

答案Whistle 提供了丰富的性能监控和分析功能,可以帮助开发者优化网络请求性能,提升用户体验。性能监控指标1. 请求时间分析Whistle 会记录每个请求的详细时间信息:DNS 解析时间:域名解析到 IP 地址的时间TCP 连接时间:建立 TCP 连接的时间SSL/TLS 握手时间:HTTPS 连接建立的时间请求发送时间:发送请求数据的时间等待时间(TTFB):服务器响应前的等待时间内容下载时间:接收响应数据的时间总请求时间:从开始到结束的总时间2. 请求大小统计请求大小:发送的请求数据大小响应大小:接收的响应数据大小压缩后大小:经过 gzip 等压缩后的数据大小压缩率:压缩前后的比例3. 状态码统计2xx 成功:成功的请求3xx 重定向:重定向请求4xx 客户端错误:客户端错误5xx 服务器错误:服务器错误性能分析功能1. 请求瀑布图Whistle 提供可视化的请求瀑布图,可以:查看请求的并行和串行关系识别性能瓶颈分析资源加载顺序发现阻塞请求2. 性能报告生成详细的性能报告,包括:总请求数总数据量平均请求时间最慢的请求列表最大的资源列表性能评分3. 对比分析可以对比不同时间段的性能数据:历史性能对比不同环境性能对比优化前后对比性能优化建议1. 减少请求数量问题: 请求过多导致加载时间过长解决方案:合并多个小文件使用雪碧图合并图片使用内联资源使用 HTTP/2 多路复用Whistle 配置示例:# 合并多个 CSS 文件style1.css resBody://{combined-styles.css}style2.css resBody://{combined-styles.css}2. 启用压缩问题: 资源文件过大解决方案:启用 gzip 压缩使用 Brotli 压缩优化图片格式Whistle 配置示例:www.example.com resHeaders://{compression-headers.json}compression-headers.json:{ "Content-Encoding": "gzip"}3. 优化缓存策略问题: 重复请求相同资源解决方案:设置合适的缓存头使用 ETag使用 Last-Modified实现本地存储Whistle 配置示例:www.example.com/static/* resHeaders://{cache-headers.json}cache-headers.json:{ "Cache-Control": "max-age=31536000", "Expires": "Wed, 21 Oct 2025 07:28:00 GMT"}4. 减少 DNS 查询问题: 多个域名导致多次 DNS 查询解决方案:减少域名数量使用 DNS 预解析使用 CDNWhistle 配置示例:# DNS 预解析www.example.com reqHeaders://{dns-prefetch.json}5. 优化图片加载问题: 图片文件过大或加载顺序不合理解决方案:使用 WebP 格式实现懒加载使用响应式图片优化图片质量Whistle 配置示例:*.jpg resBody://{optimized-image.jpg}*.png resBody://{optimized-image.png}性能监控实践1. 建立性能基准记录初始性能数据设定性能目标定期进行性能测试2. 持续监控设置性能告警定期生成性能报告跟踪性能趋势3. 问题定位使用 whistle 定位性能问题:查看慢请求按请求时间排序分析慢请求的原因优化慢请求分析大文件按响应大小排序优化大文件考虑分片加载检查错误请求查看 4xx 和 5xx 错误修复错误请求优化错误处理高级性能分析1. 使用 resScript 分析module.exports = function(req, res) { const startTime = Date.now(); const originalEnd = res.end; res.end = function(chunk, encoding) { const endTime = Date.now(); const duration = endTime - startTime; console.log(`Request ${req.url} took ${duration}ms`); console.log(`Response size: ${chunk ? chunk.length : 0} bytes`); originalEnd.call(res, chunk, encoding); };};2. 性能数据导出Whistle 支持导出性能数据:导出为 CSV 格式导出为 JSON 格式导出为 HAR 格式3. 集成性能监控工具集成 Google Lighthouse集成 WebPageTest集成自定义监控系统最佳实践定期性能测试建立性能测试流程使用自动化测试工具记录测试结果性能目标设定设定合理的性能目标分阶段优化持续改进团队协作分享性能数据建立性能规范定期性能评审文档记录记录优化过程总结优化经验建立知识库
阅读 0·2月21日 16:25