|
| 1 | +package api |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "context" |
| 6 | + "encoding/json" |
| 7 | + "fmt" |
| 8 | + "io" |
| 9 | + "net/http" |
| 10 | + "net/url" |
| 11 | + "strings" |
| 12 | + |
| 13 | + "github.com/404tk/cloudtoolkit/pkg/providers/gcp/auth" |
| 14 | +) |
| 15 | + |
| 16 | +type Request struct { |
| 17 | + Method string |
| 18 | + BaseURL string |
| 19 | + Path string |
| 20 | + Query url.Values |
| 21 | + Headers http.Header |
| 22 | + Body []byte |
| 23 | + Idempotent bool |
| 24 | +} |
| 25 | + |
| 26 | +type Option func(*Client) |
| 27 | + |
| 28 | +type Client struct { |
| 29 | + tokenSource *auth.TokenSource |
| 30 | + httpClient *http.Client |
| 31 | + retryPolicy RetryPolicy |
| 32 | +} |
| 33 | + |
| 34 | +func NewClient(ts *auth.TokenSource, opts ...Option) *Client { |
| 35 | + client := &Client{ |
| 36 | + tokenSource: ts, |
| 37 | + httpClient: NewHTTPClient(), |
| 38 | + retryPolicy: DefaultRetryPolicy(), |
| 39 | + } |
| 40 | + for _, opt := range opts { |
| 41 | + opt(client) |
| 42 | + } |
| 43 | + return client |
| 44 | +} |
| 45 | + |
| 46 | +func WithHTTPClient(hc *http.Client) Option { |
| 47 | + return func(c *Client) { |
| 48 | + if hc != nil { |
| 49 | + c.httpClient = hc |
| 50 | + } |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +func WithRetryPolicy(p RetryPolicy) Option { |
| 55 | + return func(c *Client) { |
| 56 | + if p != nil { |
| 57 | + c.retryPolicy = p |
| 58 | + } |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +func (c *Client) Do(ctx context.Context, req Request, out any) error { |
| 63 | + if ctx == nil { |
| 64 | + ctx = context.Background() |
| 65 | + } |
| 66 | + if c.tokenSource == nil { |
| 67 | + return fmt.Errorf("gcp client: nil token source") |
| 68 | + } |
| 69 | + |
| 70 | + token, err := c.tokenSource.Token(ctx) |
| 71 | + if err != nil { |
| 72 | + return err |
| 73 | + } |
| 74 | + |
| 75 | + method := strings.ToUpper(strings.TrimSpace(req.Method)) |
| 76 | + if method == "" { |
| 77 | + method = http.MethodGet |
| 78 | + } |
| 79 | + requestURL, err := resolveURL(req.BaseURL, req.Path, req.Query) |
| 80 | + if err != nil { |
| 81 | + return err |
| 82 | + } |
| 83 | + |
| 84 | + headers := cloneHeader(req.Headers) |
| 85 | + headers.Set("Authorization", "Bearer "+token.AccessToken) |
| 86 | + if req.Body != nil && strings.TrimSpace(headers.Get("Content-Type")) == "" { |
| 87 | + headers.Set("Content-Type", "application/json; charset=UTF-8") |
| 88 | + } |
| 89 | + |
| 90 | + httpResp, err := c.retryPolicy.Do(ctx, req.Idempotent, func() (*http.Response, error) { |
| 91 | + httpReq, err := http.NewRequestWithContext(ctx, method, requestURL, bytes.NewReader(req.Body)) |
| 92 | + if err != nil { |
| 93 | + return nil, err |
| 94 | + } |
| 95 | + httpReq.Header = headers.Clone() |
| 96 | + return c.httpClient.Do(httpReq) |
| 97 | + }) |
| 98 | + if err != nil { |
| 99 | + return err |
| 100 | + } |
| 101 | + defer closeResponse(httpResp) |
| 102 | + |
| 103 | + body, err := io.ReadAll(httpResp.Body) |
| 104 | + if err != nil { |
| 105 | + return fmt.Errorf("read gcp response: %w", err) |
| 106 | + } |
| 107 | + if err := DecodeError(httpResp.StatusCode, body); err != nil { |
| 108 | + return err |
| 109 | + } |
| 110 | + if out == nil || len(body) == 0 || httpResp.StatusCode == http.StatusNoContent { |
| 111 | + return nil |
| 112 | + } |
| 113 | + if err := json.Unmarshal(body, out); err != nil { |
| 114 | + return fmt.Errorf("decode gcp response: %w", err) |
| 115 | + } |
| 116 | + return nil |
| 117 | +} |
| 118 | + |
| 119 | +func resolveURL(baseURL, path string, query url.Values) (string, error) { |
| 120 | + baseURL = strings.TrimRight(strings.TrimSpace(baseURL), "/") |
| 121 | + if baseURL == "" { |
| 122 | + return "", fmt.Errorf("gcp client: empty base url") |
| 123 | + } |
| 124 | + parsed, err := url.Parse(baseURL + ensureLeadingSlash(path)) |
| 125 | + if err != nil { |
| 126 | + return "", err |
| 127 | + } |
| 128 | + parsed.RawQuery = cloneValues(query).Encode() |
| 129 | + return parsed.String(), nil |
| 130 | +} |
| 131 | + |
| 132 | +func cloneHeader(headers http.Header) http.Header { |
| 133 | + if headers == nil { |
| 134 | + return http.Header{} |
| 135 | + } |
| 136 | + return headers.Clone() |
| 137 | +} |
| 138 | + |
| 139 | +func cloneValues(values url.Values) url.Values { |
| 140 | + if values == nil { |
| 141 | + return url.Values{} |
| 142 | + } |
| 143 | + cloned := make(url.Values, len(values)) |
| 144 | + for key, items := range values { |
| 145 | + cloned[key] = append([]string(nil), items...) |
| 146 | + } |
| 147 | + return cloned |
| 148 | +} |
| 149 | + |
| 150 | +func ensureLeadingSlash(path string) string { |
| 151 | + path = strings.TrimSpace(path) |
| 152 | + if path == "" { |
| 153 | + return "/" |
| 154 | + } |
| 155 | + if strings.HasPrefix(path, "/") { |
| 156 | + return path |
| 157 | + } |
| 158 | + return "/" + path |
| 159 | +} |
| 160 | + |
| 161 | +func closeResponse(resp *http.Response) { |
| 162 | + if resp == nil || resp.Body == nil { |
| 163 | + return |
| 164 | + } |
| 165 | + _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 8<<10)) |
| 166 | + _ = resp.Body.Close() |
| 167 | +} |
0 commit comments