This repository has been archived by the owner on Jun 2, 2023. It is now read-only.
/
client.go
68 lines (54 loc) · 1.57 KB
/
client.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
package httputils
import (
"context"
"fmt"
"io"
"github.com/golangci/golangci-api/pkg/worker/analytics"
"github.com/levigross/grequests"
)
//go:generate mockgen -package httputils -source client.go -destination client_mock.go
type Client interface {
Get(ctx context.Context, url string) (io.ReadCloser, error)
Put(ctx context.Context, url string, jsonObj interface{}) error
}
type GrequestsClient struct {
header map[string]string
}
func NewGrequestsClient(header map[string]string) *GrequestsClient {
return &GrequestsClient{
header: header,
}
}
func (c GrequestsClient) Get(ctx context.Context, url string) (io.ReadCloser, error) {
resp, err := grequests.Get(url, &grequests.RequestOptions{
Context: ctx,
Headers: c.header,
})
if err != nil {
return nil, fmt.Errorf("unable to make GET http request %q: %s", url, err)
}
if !resp.Ok {
if cerr := resp.Close(); cerr != nil {
analytics.Log(ctx).Warnf("Can't close %q response: %s", url, cerr)
}
return nil, fmt.Errorf("got error code from %q: %d", url, resp.StatusCode)
}
return resp, nil
}
func (c GrequestsClient) Put(ctx context.Context, url string, jsonObj interface{}) error {
resp, err := grequests.Put(url, &grequests.RequestOptions{
Context: ctx,
Headers: c.header,
JSON: jsonObj,
})
if err != nil {
return fmt.Errorf("unable to make PUT http request %q: %s", url, err)
}
if !resp.Ok {
if cerr := resp.Close(); cerr != nil {
analytics.Log(ctx).Warnf("Can't close %q response: %s", url, cerr)
}
return fmt.Errorf("got error code from %q: %d", url, resp.StatusCode)
}
return nil
}