forked from jpillora/overseer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fetcher_http.go
80 lines (75 loc) · 1.84 KB
/
fetcher_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
74
75
76
77
78
79
80
package fetcher
import (
"fmt"
"io"
"net/http"
"time"
)
//HTTPFetcher uses HEAD requests to poll the status of a given
//file. If it detects this file has been updated, it will fetch
//and return its io.Reader stream.
type HTTP struct {
//URL to poll for new binaries
URL string
Interval time.Duration
CheckHeaders []string
//interal state
delay bool
lasts map[string]string
}
//if any of these change, the binary has been updated
var defaultHTTPCheckHeaders = []string{"ETag", "If-Modified-Since", "Last-Modified", "Content-Length"}
func (h *HTTP) Init() error {
//apply defaults
if h.URL == "" {
return fmt.Errorf("URL required")
}
h.lasts = map[string]string{}
if h.Interval == 0 {
h.Interval = 5 * time.Minute
}
if h.CheckHeaders == nil {
h.CheckHeaders = defaultHTTPCheckHeaders
}
return nil
}
func (h *HTTP) Fetch() (io.Reader, error) {
//delay fetches after first
if h.delay {
time.Sleep(h.Interval)
}
h.delay = true
//status check using HEAD
resp, err := http.Head(h.URL)
if err != nil {
return nil, fmt.Errorf("HEAD request failed (%s)", err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("HEAD request failed (status code %d)", resp.StatusCode)
}
//if all headers match, skip update
matches, total := 0, 0
for _, header := range h.CheckHeaders {
if curr := resp.Header.Get(header); curr != "" {
if last, ok := h.lasts[header]; ok && last == curr {
matches++
}
h.lasts[header] = curr
total++
}
}
if matches == total {
return nil, nil //skip, file match
}
//binary fetch using GET
resp, err = http.Get(h.URL)
if err != nil {
return nil, fmt.Errorf("GET request failed (%s)", err)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("GET request failed (status code %d)", resp.StatusCode)
}
//success!
return resp.Body, nil
}