假设我们使用标准库中的net/http和encoding/json包来请求和解析JSON响应,那么我们可以先发送GET请求:
import (
"net/http"
"io/ioutil"
)
resp, err := http.Get("https://stats.labs.apnic.net/cgi-bin/aspop?c=TH&w=120&f=j")
if err != nil {
// handle error
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
}
现在,我们已经得到了JSON响应的字节切片。下一步是解析这个字节切片成为一个结构体。
根据API文档,响应的JSON结构如下:
{
"timestamp": "2020-01-01T00:00:00Z",
"data": [
{ "asn": 1234, "name": "AS1234", "count_v4": 100, "count_v6": 10 },
{ ... },
...
]
}
那么我们可以定义一个结构体类型来映射这个JSON对象:
type ASData struct {
ASN int `json:"asn"`
Name string `json:"name"`
CountV4 int `json:"count_v4"`
CountV6 int `json:"count_v6"`
}
type ASResponse struct {
Timestamp string `json:"timestamp"`
Data []ASData `json:"data"`
}
最后,我们可以使用encoding/json包将响应字节切片解析成为一个ASResponse对象:
var response ASResponse
if err := json.Unmarshal(body, &response); err != nil {
// handle error
}
现在,我们就可以通过response对象来访问响应中的数据了。例如:
fmt.Println(response.Timestamp)
for _, data := range response.Data {
fmt.Printf("%d %s v4:%d v6:%d\n", data.ASN, data.Name, data.CountV4, data.CountV6)
}




