go实现rest服务解析

目标:解析百度交通拥堵道路排名的服务,并转成自己格式的服务

func RoadRank(cityCode string) (*StatisticResult, error) {
    if cityCode == "" {
        return nil, errors.New("参数cityCode为空")
    }

    url := fmt.Sprintf(`http://jiaotong.baidu.com/trafficindex/city/roadrank?cityCode=%s&roadtype=0`, cityCode)
    resp, err := http.Get(url)
    if err != nil {
        return nil, nil
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        return nil, nil
    }

    respResult := CongestionRespResult{}
    err = json.Unmarshal(body, &respResult)
    if err != nil {
        return nil, err
    }

    result := NewStatisticResult()
    if len(respResult.Data.List) == 0 {
        return result, nil
    }

    for _, item := range respResult.Data.List {
        result.X = append(result.X, item.Roadname)
        result.Y = append(result.Y, item.Index)
    }

    return result, nil
}

你可能感兴趣的:(go语言)