网络接口检测

背景说明

对网络接口来说为了在出问题时能第一时间知道,通常需要以一定频次进行访问并检测其返回值,以百度天气接口为例,其正常情况下返回如下:

{ "errno": 0,
"error": "",
"fingerprint": "1437903491.7985",
"data": { "weather": { "key": "北京天气",
"title": "北京天气预报一周天气预报中国天气网",
"list": [
{
"time": "周日 07月26日 (实时:33℃)",
"pic": "http://s1.bdstatic.com/r/www/aladdin/img/new_weath/bigicon/5.png",
"weather": "多云",
"wind": "微风",
"temp": "33~23℃",
"curtemp": "33℃"
},
{
"time": "周一",
"pic": "http://s1.bdstatic.com/r/www/aladdin/img/ new_weath/icon/30.png",
"weather": "雷阵雨转小到中雨",
"wind": "微风", "temp": "32~23℃"
},
{
"time": "周二",
"pic": "http://s1.bdstatic.com/r/www/aladdin/img/new_weath/icon/9.png",
"weather": "小到中雨转雷阵雨",
"wind": "微风",
"temp": "30~23℃"
},
{
"time": "周三",
"pic": "http://s1.bdstatic.com/r/www/aladdin/img/new_weath/icon/30.png",
"weather": "雷阵雨",
"wind": "微风",
"temp": "28~22℃"
},
{
"time": "周四",
"pic": "http://s1.bdstatic.com/r/www/aladdin/img/new_weath/icon/30.png",
"weather": "雷阵雨转多云",
"wind": "微风",
"temp": "32~22℃"
}
],
"support": "中国气象局2015年07月26日17时发布",
"showurl": "www.weather.com.cn/"
},
"pm2_5": {
"key": "北京pm2.5",
"title": "北京市空气质量指数实时查询
北京市环境保护监测中心",
"value": "118",
"levelnum": "3",
"level": "轻度污染",
"tip": "敏感人群症状易加剧,应避免高强度户外锻炼,外出时做好防护措施。",
"time": "2015年07月26日16时",
"resource": "北京市环境保护监测中心"
}
}
}

问题分析

考虑到接口返回是一个json数据,我们需要借助一个外部的jq命令来进行数据的解析,因为仅仅是轻量级的可用性检测,不用设计其中的业务逻辑,所以只需确保接口可返回数据,并且其中的错误码为0即可。

解决方案

case_3-1.awk

BEGIN{
    # 请求接口数据
    url = "http://uil.cbs.baidu.com/lbs/weather?resource=weather,pm2.5&city=%E5%8C%97%E4%BA%AC";
    cmd = "curl -s " url;
    cmd | getline jsonStr;
    close(cmd);

    # 使用jq命令提取errno的值
    cmd = "echo '" jsonStr "'|/usr/local/bin/jq '.errno'";
    cmd |getline errno;
    close(cmd);

    # 检查字段值
    if ( 0 == length(errno) || 0 != strtonum(errno) ) {
            print("API check failed");
    } else {
            print("API status ok");
    }
}

$awk -f case_3-1.awk
API status ok

程序首先通过curl获取到接口返回字符串,再通过jq解析errno字段进行判断,这里要注意的是接口可能出错返回空,jq解析也会因为json格式错误或是字段不存在返回空,所以需要先进行空判断。

results matching ""

    No results matching ""