使用Golang来调用API

第一次尝试Golang

我打算使用Golang编写一个API服务器,首先尝试了一下访问日本的WeatherHacks API。

由于JSON解析似乎很复杂,所以这次只做到数据获取。

代码 (Mandarin Chinese)

package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
    "net/url"
)

func main() {
    values := url.Values{}
    values.Add("city", "400040")
    resp, err := http.Get("http://weather.livedoor.com/forecast/webservice/json/v1" + "?" + values.Encode())

    if err != nil {
        fmt.Println(err)
        return
    }

    defer resp.Body.Close()

    execute(resp)
}

func execute(response *http.Response) {
    body, err := ioutil.ReadAll(response.Body)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(string(body))
}

Outcome

{"pinpointLocations":[{"link":"http://weather.livedoor.com/area/forecast/4020200","name":"\u5927\u725f\u7530\u5e02"},{"link":"http://weather.livedoor.com/area/forecast/4020300","name":"\u4e45\u7559\u7c73\u5e02"},{"link":"http://weather.livedoor.com/area/forecast/4020700","name":"\u67f3\u5ddd\u5e02"},{"link":"http://weather.livedoor.com/area/forecast/4021000","name":"\u516b\u5973\u5e02"},{"link":"http://weather.livedoor.com/area/forecast/4021100","name":"\u7b51\u5f8c\u5e02"},{"link":"http://weather.livedoor.com/area/forecast/4021200","name":"\u5927\u5ddd\u5e02"},{"link":"http://weather.livedoor.com/area/forecast/4021600","name":"\u5c0f\u90e1\u5e02"},{"link":"http://weather.livedoor.com/area/forecast/4022500","name":"\u3046\u304d\u306f\u5e02"},{"link":"http://weather.livedoor.com/area/forecast/4022800","name":"\u671d\u5009\u5e02"},{"link":"http://weather.livedoor.com/area/forecast/4022900","name":"\u307f\u3084\u307e\u5e02"},{"link":"http://weather.livedoor.com/area/forecast/4044700","name":"\u7b51\u524d\u753a"},{"link":"http://weather.livedoor.com/area/forecast/4044800","name":"\u6771\u5cf0\u6751"},{"link":"http://weather.livedoor.com/area/forecast/4050300","name":"\u5927\u5200\u6d17\u753a"},{"link":"http://weather.livedoor.com/area/forecast/4052200","name":"\u5927\u6728\u753a"},{"link":"http://weather.livedoor.com/area/forecast/4054400","name":"\u5e83\u5ddd\u753a"}]

以下略
广告
将在 10 秒后关闭
bannerAds