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

whistle 的规则语法是什么,常用的操作符有哪些?

2月21日 16:25

答案

Whistle 的规则语法非常简洁直观,基本格式为:pattern operator-uri

基本规则格式

shell
pattern operator-uri
  • pattern:匹配模式,可以是域名、路径、正则表达式等
  • operator:操作符,指定要执行的操作类型
  • uri:目标地址或参数

常用操作符

  1. host:修改请求的 Host 头

    shell
    www.example.com host 127.0.0.1:8080
  2. reqHeaders:修改请求头

    shell
    www.example.com reqHeaders://{custom-headers.json}
  3. resHeaders:修改响应头

    shell
    www.example.com resHeaders://{cors-headers.json}
  4. resBody:修改响应体

    shell
    www.example.com resBody://{mock-data.json}
  5. resReplace:替换响应内容

    shell
    www.example.com resReplace://old-string/new-string
  6. reqScript:使用脚本处理请求

    shell
    www.example.com reqScript://{request-handler.js}
  7. resScript:使用脚本处理响应

    shell
    www.example.com resScript://{response-handler.js}
  8. forward:转发请求到指定地址

    shell
    www.example.com forward https://api.example.com

匹配模式示例

  1. 精确匹配域名

    shell
    www.example.com operator-uri
  2. 通配符匹配

    shell
    *.example.com operator-uri
  3. 路径匹配

    shell
    www.example.com/api/* operator-uri
  4. 正则表达式

    shell
    /^https:\/\/www\.example\.com\/api\/.*/ operator-uri

规则优先级

Whistle 按照规则在配置文件中的顺序从上到下匹配,一旦匹配成功就不再继续匹配后续规则。因此,更具体的规则应该放在前面。

注释和分组

  • 使用 # 添加注释
  • 使用 # group-name 创建分组,便于管理大量规则
标签:Whistle