-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
96 lines (79 loc) · 2.34 KB
/
Copy pathclient.go
File metadata and controls
96 lines (79 loc) · 2.34 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package airbytesdk
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"github.com/evris99/airbyte-sdk/types"
)
var (
ErrInvalidEndpoint = errors.New("invalid api endpoint")
ErrServer = errors.New("airbyte server error")
ErrInvalidStatus = errors.New("invalid server response status code")
)
// A client to interact with the airbyte API using HTTP
type Client struct {
// The underlying HTTP Client
HttpClient *http.Client
endpoint *url.URL
}
// Creates and returns a new airbyte API client
func New(apiEndpoint string) (*Client, error) {
_, err := url.ParseRequestURI(apiEndpoint)
if err != nil {
return nil, fmt.Errorf("could not parse URL: %w", err)
}
endpoint, err := url.Parse(apiEndpoint)
if err != nil || endpoint.Scheme == "" || endpoint.Host == "" {
return nil, fmt.Errorf("could not parse URL: %w", err)
}
return &Client{
HttpClient: &http.Client{},
endpoint: endpoint,
}, nil
}
// Makes an HTTP API request with the give data as body
func (c *Client) makeRequest(ctx context.Context, u *url.URL, data interface{}) (*http.Response, error) {
// If the data exists encode it to json
var httpBodyReader io.Reader
if data != nil {
jsonData, err := json.Marshal(data)
if err != nil {
return nil, fmt.Errorf("could not encode data: %w", err)
}
httpBodyReader = bytes.NewReader(jsonData)
}
req, err := http.NewRequestWithContext(ctx, "POST", u.String(), httpBodyReader)
if err != nil {
return nil, fmt.Errorf("could not create request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
res, err := c.HttpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("could not execute request: %w", err)
}
// If response code is not 2XX return error
if res.StatusCode >= 300 || res.StatusCode < 200 {
return nil, getErrorResponse(res)
}
return res, nil
}
// Receives an HTTP response with a non 2XX status code
// And returns the according error
func getErrorResponse(res *http.Response) error {
if res.StatusCode >= 400 && res.StatusCode < 600 {
responseError, err := types.ResponseErrorFromJSON(res.Body)
if err != nil {
return fmt.Errorf("could not decode error response: %v", err)
}
return responseError
}
return ErrInvalidStatus
}
func appendToURL(u *url.URL, path string) (*url.URL, error) {
return u.Parse(fmt.Sprintf("%s%s", u.Path, path))
}