-
Notifications
You must be signed in to change notification settings - Fork 94
/
http.go
72 lines (61 loc) · 1.69 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
package http
import (
"context"
"crypto/sha256"
"fmt"
"io"
"net/http"
"golang.org/x/time/rate"
)
// RLHTTPClient Rate Limited HTTP Client
type RLHTTPClient struct {
Client *http.Client
Ratelimiter *rate.Limiter
}
// Do dispatches the HTTP request to the network
func (c *RLHTTPClient) Do(req *http.Request) (*http.Response, error) {
// Comment out the below 5 lines to turn off ratelimiting
err := c.Ratelimiter.Wait(req.Context()) // This is a blocking call. Honors the rate limit
if err != nil {
return nil, err
}
resp, err := c.Client.Do(req)
if err != nil {
return nil, err
}
return resp, nil
}
// NewClient return rate_limited_http client with a ratelimiter
func NewClient(rl *rate.Limiter) *RLHTTPClient {
c := &RLHTTPClient{
Client: http.DefaultClient,
Ratelimiter: rl,
}
return c
}
// GetArtifactSHA256 attempts to pull the specified artifact and generate a
// sha256 hash of it.
//
// On success, it will return the sha256 hash as a string.
func (c *RLHTTPClient) GetArtifactSHA256(ctx context.Context, artifactURI string) (string, error) {
req, err := http.NewRequestWithContext(ctx, "GET", artifactURI, nil)
if err != nil {
return "", fmt.Errorf("creating request for %s: %w", artifactURI, err)
}
var client http.Client
resp, err := client.Do(req)
if err != nil {
return "", fmt.Errorf("getting %s: %w", artifactURI, err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("%d when getting %s", resp.StatusCode, artifactURI)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", fmt.Errorf("reading body: %w", err)
}
h256 := sha256.New()
h256.Write(body)
return fmt.Sprintf("%x", h256.Sum(nil)), nil
}