forked from rs/jplot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp.go
73 lines (64 loc) · 1.15 KB
/
http.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package data
import (
"io/ioutil"
"net/http"
"time"
"github.com/elgs/gojq"
)
type httpSource struct {
c chan res
done chan struct{}
}
type res struct {
jq *gojq.JQ
err error
}
// FromHTTP fetch data points from url every interval and keep size points.
func FromHTTP(url string, interval time.Duration, size int) *Points {
h := httpSource{
c: make(chan res),
done: make(chan struct{}),
}
go h.run(url, interval)
return &Points{
Size: size,
Source: h,
}
}
func (h httpSource) run(url string, interval time.Duration) {
t := time.NewTicker(interval)
defer t.Stop()
h.fetch(url)
for {
select {
case <-t.C:
h.fetch(url)
case <-h.done:
close(h.c)
return
}
}
}
func (h httpSource) fetch(url string) {
resp, err := http.Get(url)
if err != nil {
h.c <- res{err: err}
return
}
defer resp.Body.Close()
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
h.c <- res{err: err}
return
}
jq, err := gojq.NewStringQuery(string(b))
h.c <- res{jq: jq, err: err}
}
func (h httpSource) Get() (*gojq.JQ, error) {
res := <-h.c
return res.jq, res.err
}
func (h httpSource) Close() error {
close(h.done)
return nil
}