Groovy循环匹配条件中断、批量校验接口返回200的实现问题
原有代码问题分析
- 你使用的
find方法逻辑是返回第一个匹配闭包条件的元素,当前闭包遇到200就返回true终止遍历,完全无法检测到200之后的非200状态码,和「所有接口都返回200才返回true」的需求完全相反 mytest函数没有显式指定返回值,默认取find方法的执行结果,逻辑判断完全不符合预期
修正实现方案
1. 状态码模拟校验版本
使用Groovy集合内置的every方法,该方法只有所有元素都满足闭包条件时才返回true,遇到第一个不满足条件的元素就终止遍历,刚好匹配你的需求:
def mytest() { def statusList = [200, 200, 200, 300] // 可按需添加非200状态码的打印逻辑 return statusList.every { status -> if (status != 200) { println "检测到非200状态码:${status}" return false } return true } } if (!mytest()) { println "Function returns false" }
2. 实际curl接口校验版本
直接调用系统curl命令获取状态码,适配你的真实业务场景:
// 填入需要校验的接口地址 def apiList = [ "https://example.com/api/1", "https://example.com/api/2", "https://example.com/api/3" ] def checkAllApi() { return apiList.every { apiUrl -> // curl参数说明:-s静默模式,-o /dev/null丢弃响应体,-w输出状态码,--connect-timeout设置超时时间 def curlCommand = ["curl", "-s", "-o", "/dev/null", "-w", "%{http_code}", "--connect-timeout", "5", apiUrl] def process = curlCommand.execute() process.waitFor() def httpStatus = process.text.toInteger() if (httpStatus != 200) { println "接口${apiUrl}校验失败,状态码:${httpStatus}" return false } println "接口${apiUrl}校验正常" return true } } // 执行校验 def allSuccess = checkAllApi() println "批量校验最终结果:${allSuccess}"
内容的提问来源于stack exchange,提问作者WhoAmI
相关产品推荐
相关产品推荐

