-
Notifications
You must be signed in to change notification settings - Fork 6
/
client.go
82 lines (67 loc) · 2.66 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package client
import (
"context"
"fmt"
"io"
"net/http"
"github.com/deepmap/oapi-codegen/pkg/securityprovider"
"github.com/hashicorp/go-cleanhttp"
"github.com/pkg/errors"
)
func New(ctx context.Context, apiKey, apiEndpoint, version string, opts ...ClientOption) (*ClientWithResponses, error) {
bearerTokenProvider, bearerTokenProviderErr := securityprovider.NewSecurityProviderBearerToken(apiKey)
if bearerTokenProviderErr != nil {
return nil, bearerTokenProviderErr
}
base := cleanhttp.DefaultClient()
// The generated client won't turn validation errors into actual errors, so we do this
// inside of a generic middleware.
base.Transport = Wrap(cleanhttp.DefaultTransport(), func(req *http.Request, next http.RoundTripper) (*http.Response, error) {
resp, err := next.RoundTrip(req)
if err == nil && resp.StatusCode > 299 {
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("status %d: no response body", resp.StatusCode)
}
return nil, fmt.Errorf("status %d: %s", resp.StatusCode, string(data))
}
return resp, err
})
clientOpts := append([]ClientOption{
WithHTTPClient(base),
WithRequestEditorFn(bearerTokenProvider.Intercept),
// Add a user-agent so we can tell which version these requests came from.
WithRequestEditorFn(func(ctx context.Context, req *http.Request) error {
req.Header.Add("user-agent", fmt.Sprintf("catalog-importer/%s", version))
return nil
}),
}, opts...)
client, err := NewClientWithResponses(apiEndpoint, clientOpts...)
if err != nil {
return nil, errors.Wrap(err, "creating client")
}
return client, nil
}
// WithReadOnly restricts the client to GET requests only, useful when creating a client
// for the purpose of dry-running.
func WithReadOnly() ClientOption {
return WithRequestEditorFn(func(ctx context.Context, req *http.Request) error {
if req.Method != http.MethodGet {
return fmt.Errorf("read-only client tried to make mutating request: %s %s", req.Method, req.URL.String())
}
return nil
})
}
// RoundTripperFunc wraps a function to implement the RoundTripper interface, allowing
// easy wrapping of existing round-trippers.
type RoundTripperFunc func(req *http.Request) (*http.Response, error)
func (f RoundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return f(req)
}
// Wrap allows easy wrapping of an existing RoundTripper with a function that can
// optionally call the original, or do its own thing.
func Wrap(next http.RoundTripper, apply func(req *http.Request, next http.RoundTripper) (*http.Response, error)) http.RoundTripper {
return RoundTripperFunc(func(req *http.Request) (*http.Response, error) {
return apply(req, next)
})
}