原创文章,转载请注明出处
https://qiedd.com/
在网页 API 中,通常使用 Restful API,返回的是一个 JSON,这是 B站 API 时间响应的
https://api.bilibili.com/x/report/click/now
{
"code": 0,
"message": "0",
"ttl": 1,
"data": {
"now": 1611111111
}
}在 Python 中处理起来比较容易
import requests url = 'https://api.bilibili.com/x/report/click/now' r = requests.get(url) print(r.json()['data']['now'])
只要上述代码,就可以输出当前时间戳
但是在 Go 中,如果需要输出,则需要先设置一个结构体,才能去解析 JSON
结构体必须大写
package main
import (
"fmt"
"github.com/go-resty/resty/v2"
)
type Time struct {
Data struct {
Now uint64
}
}
func main() {
c := resty.New()
result := &Time{}
_, err := c.R().
SetResult(result).
Get("https://api.bilibili.com/x/report/click/now")
if err != nil {
fmt.Println(err)
}
fmt.Println(result.Data.Now)
}
如果不需要想使用结构体,可以使用第三方库
推荐使用 GJSON: https://github.com/tidwall/gjson
package main
import (
"fmt"
"github.com/go-resty/resty/v2"
"github.com/tidwall/gjson"
)
func main() {
client := resty.New()
resp, _ := client.R().
EnableTrace().
Get("https://api.bilibili.com/x/report/click/now")
//body := resp.String()
//fmt.Println(body)
now := gjson.Get(resp.String(), "data").Get("now")
fmt.Println(now)
}
0 条评论