Docker Compose部署Wiremock:如何计算返回递增1小时的时间戳
WireMock实现基于请求日期参数的时间递增响应
问题场景
通过Docker Compose部署WireMock后,需要处理带日期参数的GET请求/nexthours?deliveryDateUtc=2024-05-20T10:00:00Z,返回包含接下来3小时递增时间戳的JSON响应,但当前模板仅能返回原始日期参数,无法实现时间递增。
当前Docker Compose配置
wiremock: image: "wiremock/wiremock:latest" ports: - "8095:8080" container_name: wiremock volumes: - ./wiremock/extensions:/var/wiremock/extensions - ./wiremock/__files:/home/wiremock/__files - ./wiremock/mappings:/home/wiremock/mappings entrypoint: ["/docker-entrypoint.sh", "--global-response-templating", "--disable-gzip", "--verbose"]
当前映射文件(mappings/nexthours.json)
{ "request": { "method": "GET", "urlPath": "/nexthours" }, "response": { "status": 200, "headers": { "Content-Type": "application/json" }, "bodyFileName": "nexthourstemplate.json", "transformers": ["response-template"] } }
当前模板文件(__files/nexthourstemplate.json)
{ "next3hours": [ {{#each (range 1 3)}} { "position": {{this}}, "timestamp": "{{request.query.deliveryDateUtc}}" }{{#unless @last}},{{/unless}} {{/each}} ] }
解决方案
需求完全可行,核心是利用WireMock响应模板的日期处理函数,对请求传入的日期参数进行增量计算。
1. 修改响应模板文件
更新__files/nexthourstemplate.json,使用parseDateTime解析日期参数,通过plusHours实现小时增量,最后用formatDateTime格式化输出:
{ "next3hours": [ {{#each (range 1 3)}} { "position": "{{this}}", "timestamp": "{{parseDateTime request.query.deliveryDateUtc 'yyyy-MM-dd''T''HH:mm:ss''Z' | plusHours (minus this 1) | formatDateTime 'yyyy-MM-dd''T''HH:mm:ss''Z'}}" }{{#unless @last}},{{/unless}} {{/each}} ] }
- 解析逻辑:
parseDateTime将请求的字符串日期转为可操作的日期对象 - 增量计算:
minus this 1是因为range 1 3生成的是1、2、3,对应需要增加0、1、2小时,匹配position与时间的对应关系 - 格式化:
formatDateTime确保输出的时间戳符合ISO 8601格式
2. 确认全局模板启用
检查Docker Compose的entrypoint参数已包含--global-response-templating(当前配置已满足),该参数是响应模板功能生效的前提。
测试验证
发起请求http://localhost:8095/nexthours?deliveryDateUtc=2024-05-20T10:00:00Z,即可得到期望的响应:
{ "next3hours":[ {"position":"1","timestamp":"2024-05-20T10:00:00Z"}, {"position":"2","timestamp":"2024-05-20T11:00:00Z"}, {"position":"3","timestamp":"2024-05-20T12:00:00Z"} ] }
内容的提问来源于stack exchange,提问作者Mathias F
相关产品推荐
相关产品推荐

