-
Notifications
You must be signed in to change notification settings - Fork 221
/
api.go
85 lines (68 loc) · 1.68 KB
/
api.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
83
84
85
package flypkgs
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
"github.com/pkg/errors"
)
func NewClient(endpoint, apiKey string) *Client {
return &Client{
BaseURL: endpoint,
apiKey: apiKey,
HTTPClient: &http.Client{
Timeout: time.Minute,
},
}
}
type successResponse struct {
Code int `json:"code"`
Data interface{} `json:"data"`
}
type Client struct {
BaseURL string
apiKey string
HTTPClient *http.Client
}
func (c *Client) URL(path string, params ...any) string {
if !strings.HasPrefix(path, "/") {
path = "/" + path
}
return fmt.Sprintf(c.BaseURL+path, params...)
}
func (c *Client) sendRequest(ctx context.Context, req *http.Request, v interface{}) error {
req = req.WithContext(ctx)
if len(req.Header.Values("Content-Type")) == 0 {
req.Header.Set("Content-Type", "application/json; charset=utf-8")
}
req.Header.Set("Accept", "application/json; charset=utf-8")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.apiKey))
res, err := c.HTTPClient.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
// // Uncomment this to print the response body for debugging
// var buf bytes.Buffer
// io.Copy(&buf, res.Body)
// fmt.Println(buf.String())
// res.Body = io.NopCloser(&buf)
if res.StatusCode < http.StatusOK || res.StatusCode >= http.StatusBadRequest {
errRes := ErrorResponse{
Code: res.StatusCode,
}
if err = json.NewDecoder(res.Body).Decode(&errRes); err != nil {
return errors.Wrap(err, "decoding error response")
}
return errRes
}
fullResponse := successResponse{
Data: v,
}
if err = json.NewDecoder(res.Body).Decode(&fullResponse); err != nil {
return err
}
return nil
}