我正在尝试轮询一个API以保留流量数据的时间序列,并在发生更改时将该数据保存到postgres。
目前,我有一个这样的实现
//this needs to check the api for new information every X seconds
func Poll(req *http.Request, client *http.Client) ([]byte, error) {
r := rand.New(rand.NewSource(99))
c := time.Tick(10 * time.Second)
for _ = range c {
//Download the current contents of the URL and do something with it
response, err := client.Do(req)
data, _ := io.ReadAll(response.Body)
if err != nil {
return nil, err
}
return data, nil
// add a bit of jitter
jitter := time.Duration(r.Int31n(5000)) * time.Millisecond
time.Sleep(jitter)
}
}
func main() {
client := &http.Client{
Timeout: time.Second * 60 * 60 * 600,
}
url := "https://data-exchange-api.vicroads.vic.gov.au/bluetooth_data/links"
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return err
}
req.Header.Set("Ocp-Apim-Subscription-Key", "xx")
// response, err := client.Do(req)
data, err := Poll(req, client)
fmt.Println(string(data))
}
接下来,我将执行比较功能。
基本上,我正在尝试找出如何确保循环首先调用查询并返回适当的值。
我认为这个实现可能不是很好,我只是不确定如何真正正确地实现它。我能得到一些指点吗?
繁星淼淼
长风秋雁
相关分类