-
Notifications
You must be signed in to change notification settings - Fork 82
/
release_monitoring.go
73 lines (63 loc) · 1.53 KB
/
release_monitoring.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 relmon
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
rlhttp "chainguard.dev/melange/pkg/http"
"github.com/pkg/errors"
"golang.org/x/time/rate"
)
const searchFmt = "https://release-monitoring.org/api/v2/projects/?name=%s&ecosystem=pypi"
type Items struct {
Items []Item `json:"items"`
}
type Item struct {
Ecosystem string `json:"ecosystem"`
Homepage string `json:"homepage"`
ID int `json:"id"`
}
func NewMonitorFinder() *MonitorFinder {
return &MonitorFinder{
Client: &rlhttp.RLHTTPClient{
Client: http.DefaultClient,
// 1 request every second to avoid DOS'ing server
Ratelimiter: rate.NewLimiter(rate.Every(1*time.Second), 1),
},
}
}
type MonitorFinder struct {
Client *rlhttp.RLHTTPClient
}
func (mf *MonitorFinder) FindMonitor(ctx context.Context, pkg string) (*Item, error) {
var Items *Items
url := fmt.Sprintf(searchFmt, pkg)
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/json")
resp, err := mf.Client.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
cause := errors.New("http status return was not 200")
err := fmt.Errorf("%d when getting %s: %w", resp.StatusCode, url, cause)
return nil, err
}
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
err = json.Unmarshal(data, &Items)
if err != nil {
return nil, err
}
if len(Items.Items) == 0 {
return nil, errors.New("no items found")
}
return &Items.Items[0], nil
}